Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #30916

Re: a simple multi-thread question

From Eric Sosman <esosman@comcast-dot-net.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: a simple multi-thread question
Date 2015-01-26 10:55 -0500
Organization A noiseless patient Spider
Message-ID <ma5o15$s9p$1@dont-email.me> (permalink)
References <60c8877a-8321-4ba5-ab9a-8ccabd77874b@googlegroups.com>

Show all headers | View raw


On 1/26/2015 10:40 AM, John wrote:
>
> I am amazed at what I saw:
>
> synchronized private void print()
> {
>       System.out.println("printing A");
>       System.out.println("printing B");
>       System.out.println("printing C");
> }
> [... he gets interleaved output ...]

     Each Java object has its own lock ("monitor"), independent of the
locks belonging to other Java objects.  When you call a synchronized
instance method, Java acquires the lock of the "this" object before
proceeding, and releases it when the method finishes.  If there are
several object instances floating around, there are several "this"
and several independent locks.

> I thought the method is atomic.

     No.  Synchronization is not about methods (or code blocks), but
about objects: You lock the *object*, not a method.  If there are
four baristas at the Starcrossed shop, you "lock" only one of them
while placing your order, you do not "lock" the entire place-an-order
procedure and keep other customers from being serviced.

     Time to re-open your textbook, I think.

-- 
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

a simple multi-thread question John <xsli2@yahoo.com> - 2015-01-26 07:40 -0800
  Re: a simple multi-thread question Arne Vajhøj <arne@vajhoej.dk> - 2015-01-26 10:53 -0500
  Re: a simple multi-thread question Robert Klemme <shortcutter@googlemail.com> - 2015-01-26 07:54 -0800
  Re: a simple multi-thread question Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-01-26 10:55 -0500
    Re: a simple multi-thread question Robbie Brown <rob@example.com> - 2015-01-26 18:05 +0000
      Re: a simple multi-thread question Robbie Brown <rob@example.com> - 2015-01-26 18:08 +0000
        Re: a simple multi-thread question Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-01-26 17:19 -0500
      Re: a simple multi-thread question Arne Vajhøj <arne@vajhoej.dk> - 2015-01-26 13:27 -0500
        Re: a simple multi-thread question Robbie Brown <rob@example.com> - 2015-01-26 19:51 +0000
  Re: a simple multi-thread question Jukka Lahtinen <jtfjdehf@hotmail.com.invalid> - 2015-01-28 21:55 +0200

csiph-web