Java multi-thread synchronization example and object Lock Mechanism

Source: Internet
Author: User

  Java MultithreadingThe synchronization depends onObject Lock MechanismThe synchronized keyword uses blocking to achieve mutex access to shared resources.


The following is a simple example for comparative analysis. The task to be done by the instance is very simple, that is, to create 10 threads. Each thread prints the 100 numbers from 0 to 99. We hope there will be no cross-and disorderly printing between threads, it is printed sequentially.


First, let's take a look at the first piece of code. Here we add the synchronized keyword to the run () method. We hope to allow mutex access to the run method, but the result is not as expected, this is because synchronized locks this object, that is, the current running thread object itself. 10 threads are created in the code, and each thread holds the object lock of this object, which cannot synchronize threads.


Code


Package com. vista;


Class MyThread implements java. lang. Runnable


{


Private int threadId;


Public MyThread (int id)


{


This. threadId = id;


}


@ Override


Public synchronized void run ()


{


For (int I = 0; I <100; ++ I)


{


System. out. println ("Thread ID:" + this. threadId + ":" + I );


}


}


}


Public class ThreadDemo


{


/**


* @ Param args


* @ Throws InterruptedException


*/


Public static void main (String [] args) throws InterruptedException


{


For (int I = 0; I <10; ++ I)


{


New Thread (new MyThread (I )). Start ();


Thread. sleep (1 );


}


}


}


From the code segment above, we can know that to synchronize threads, these threads must compete for a unique shared object lock.


Based on this idea, we will modify the first code as follows. Before creating a startup thread, we will first create an Object for competition between threads, then pass the reference of this Object to the lock member variable of each thread Object. In this way, the lock members of each thread point to the same Object. In the run method, we use the synchronzied block to partially block the lock object, so that the thread can compete for this unique shared object lock to achieve synchronization.


Code


Package com. vista;


Class MyThread implements java. lang. Runnable


{


Private int threadId;


Private Object lock;


Public MyThread (int id, Object obj)


{


This. threadId = id;


This. lock = obj;


}


@ Override


Public void run ()


{


Synchronized (lock)


{


For (int I = 0; I <100; ++ I)


{


System. out. println ("Thread ID:" + this. threadId + ":" + I );


}


}


}


}


Public class ThreadDemo


{


/**


* @ Param args


* @ Throws InterruptedException


*/


Public static void main (String [] args) throws InterruptedException


{


Object obj = new Object ();


For (int I = 0; I <10; ++ I)


{


New Thread (new MyThread (I, obj )). Start ();


Thread. sleep (1 );


}


}


}


From the second code, we can see that the key to synchronization is that multiple thread objects compete for the same shared resource. The above Code creates shared resources externally and passes them to the thread for implementation. We can also use the class member variables shared by all class instances, so we can implement the lock with static member objects. The Code is as follows:


Code


Package com. vista;


Class MyThread implements java. lang. Runnable


{


Private int threadId;


Private static Object lock = new Object ();


Public MyThread (int id)


{


This. threadId = id;


}


@ Override


Public void run ()


{


Synchronized (lock)


{


For (int I = 0; I <100; ++ I)


{


System. out. println ("Thread ID:" + this. threadId + ":" + I );


}


}


}


}


Public class ThreadDemo


{


/**


* @ Param args


* @ Throws InterruptedException


*/


Public static void main (String [] args) throws InterruptedException


{


For (int I = 0; I <10; ++ I)


{


New Thread (new MyThread (I )). Start ();


Thread. sleep (1 );


}


}


}


Let's take a look at the first piece of code. The sychronized keyword is added to the instance method to block this object, while the sychronized keyword is added to the static method to block the class itself. Static methods are shared by all class instance objects. Therefore, when a thread object accesses this static method, it is mutually exclusive to achieve thread synchronization. The Code is as follows:


Code


Package com. vista;


Class MyThread implements java. lang. Runnable


{


Private int threadId;


Public MyThread (int id)


{


This. threadId = id;


}


@ Override


Public void run ()


{


TaskHandler (this. threadId );


}


Private static synchronized void taskHandler (int threadId)


{


For (int I = 0; I <100; ++ I)


{


System. out. println ("Thread ID:" + threadId + ":" + I );


}


}


}


Public class ThreadDemo


{


/**


* @ Param args


* @ Throws InterruptedException


*/


Public static void main (String [] args) throws InterruptedException


{


For (int I = 0; I <10; ++ I)


{


New Thread (new MyThread (I )). Start ();


Thread. sleep (1 );


}


}


}

 

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.