Java synchronization and mutex (1)

Source: Internet
Author: User

All objects automatically contain a single lock, that is, all objects have only a unique lock. Therefore, when a task (thread) accesses a Class A that contains sycnhronized, so before this thread returns from this method (that is, before the current thread finishes executing this method ), other methods marked with this keyword in Class A will be blocked in other threads.
In layman's terms, when a's method containing synchronized is called, a will be shackled. At this time, other methods containing synchronized in a will be called only after the previous method is called and the lock is released.

For more information, see <Java synchronization and mutex

Next let's look at the specific program. The field num in timer is a shared resource.

Public class testsync implements runnable {timer = new timer (); public static void main (string [] ARGs) {testsync test = new testsync (); thread T1 = new thread (TEST); thread t2 = new thread (TEST); t1.setname ("T1"); t2.setname ("T2"); t1.start (); t2.start ();} public void run () {timer. add (thread. currentthread (). getname () ;}} class timer {Private Static int num = 0; Public void add (string name) {num ++; try {thread. sleep (1);} catch (interruptedexception e) {} system. out. println (name + ", you are the" + num + "thread using timer ");}}

The running result is as follows:

T1, you are the first thread to use Timer

T2, you are 2nd threads using Timer

That is to say, when the thread runs to num ++, thread 2 is interrupted. Because incremental and progressive operations in Java are not atomic operations, even if sleep is not called in this program, this can also be interrupted.

Next let's take a look at the synchronization effect.

Public void add (string name) {synchronized (this) {// synchronize num ++; try {thread. sleep (1000);} catch (interruptedexception e) {} system. out. println (name + ", you are the" + num + "thread using timer ");}}

The running result is correct.

T1, you are the first thread to use Timer

T2, you are 2nd threads using Timer

However, to illustrate the problem, change the run method in testsync to the following:

Public void run () {// time. add (thread. currentthread (). getname (); try {thread. sleep (1000); // to display the result, let it sleep for one second} catch (interruptedexception ex) {logger. getlogger (testsync. class. getname ()). log (level. severe, null, ex);} system. out. println (thread. currentthread (). getname () + "----");}

Then, this operation is

T1, you are the first thread to use Timer

T2, you are 2nd threads using Timer

T1 --------

T2 --------

Instead of what you think

T1, you are the first thread to use Timer
T1 ----
T2, you are 2nd threads using Timer
T2 ----

The reason is that when thread T1 is sleeping, thread T2 switches in and executes the task once. How can we get the correct result, next we will make the following improvements to the run method in testsync to get the expected results.

 public void run() {       synchronized(time){            time.add(Thread.currentThread().getName());            try {                Thread.sleep(3000);            } catch (InterruptedException ex) {                Logger.getLogger(TestSync.class.getName()).log(Level.SEVERE, null, ex);            }          System.out.println(Thread.currentThread().getName() + "----");        }    }

Because T1 first obtains the time lock, T2. even if sleep () does not execute the synchronization block in run, T2. because T2, and the sleep () operation does not release the lock (this is also a huge difference with wait)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.