Multithreading synchronization problem with synchronized keyword in Java

Source: Internet
Author: User
Tags instance method

multithreading synchronization problem with synchronized keyword in Java

in Java, multi-threading synchronization relies on the object lock mechanism, the Synchronized keyword is the use of encapsulating object locks to achieve mutually exclusive access to shared resources.
The following is a simple example of multithreading synchronization problem, we want to add the Synchronized keyword in the run () method to achieve mutually exclusive access.
Package Com.clark.thread;public class MyThread implements runnable{private int threadId;    public MyThread (int id) {this.threadid = ID;  } @Override public synchronized void Run () {//At this time the keyword synchronized is locked by the This object, that is, the currently running thread object itself for (int i = 0; I < 100;            i++) {if (i% ==0) {System.out.println ();        } System.out.print ("Thread ID:" +this.threadid+ ":" +i+ ""); }    }}
Test class:
Package Com.clark.thread;public class Threaddemo {public static void main (string[] args) throws Interruptedexception {
   //code, and each thread holds an object lock on this object, which does not enable thread synchronization. for                (int i = 0; i < i++) {new Thread (new MyThread (i)). Start (); Thread.Sleep (1); }}}
The Print Results section is as follows: Its threads are not mutually exclusive access. Therefore did not achieve the resource multithreading synchronization effect ...
from the above, to realize thread synchronization, these threads must be allowed to compete for a unique shared object lock.
Package Com.clark.thread;public class MyThread implements Runnable{private int threadid;private Object object;// Object locks between threads used by public MyThread (int Id,object object) {This.threadid = Id;this.object = object;} @Overridepublic  void Run () {/** * passes a reference to the object object to the lock member variable of each thread's objects * so that each thread's lock member points to the same object object * This allows the thread to compete for this unique shared object lock for synchronization. */synchronized (object) {for (int i = 0; i <; i++) {if (i% ==0) {System.out.println ();} System.out.print ("Thread ID:" +this.threadid+ ":" +i+ "");}}}}
Package Com.clark.thread;public class Threaddemo {public static void main (string[] args) throws Interruptedexception {OBJ ECT obj = new Object (); for (int i = 0; i < i++) {new Thread (new MyThread (I,obj)). Start (); Thread.Sleep (1);}}
The test results are as follows:
Thread id:5:60 thread id:5:61 thread id:5:62 thread id:5:63 thread id:5:64 thread id:5:65 thread id:5:66 thread id:5:67 Th Read id:5:68 thread id:5:69 thread id:5:70 thread id:5:71 thread id:5:72 thread id:5:73 thread id:5:74 thread id:5:75 thre  Ad id:5:76 thread id:5:77 thread id:5:78 thread id:5:79 thread id:5:80 thread id:5:81 thread id:5:82 thread id:5:83 thread id:5:84 thread id:5:85 thread id:5:86 thread id:5:87 thread id:5:88 thread id:5:89 thread id:5:90 thread id:5:91 thread I d:5:92 thread id:5:93 thread id:5:94 thread id:5:95 thread id:5:96 thread id:5:97 thread id:5:98 thread id:5:99 thread ID:  6:0 thread id:6:1 thread id:6:2 thread id:6:3 thread id:6:4 thread id:6:5 thread id:6:6 thread id:6:7 thread Id:6:8 thread Id:6:9 thread id:6:10 thread id:6:11 thread id:6:12 thread id:6:13 thread id:6:14 thread id:6:15 thread id:6:16 thread ID : 6:17 thread id:6:18 thread id:6:19 thread id:6:20 thread id:6:21 thread id:6:22 thread id:6:23 thread id:6:24 thread Id:6 : Thread id:6:26 Thread id:6:27 thread id:6:28 thread id:6:29  

The second code shows that the key to synchronization is that multiple thread objects compete for the same shared resource, and the code above is implemented externally by creating shared resources and then passing them to the thread. We can also use class member variables to share this feature with instances of all classes, so you can Lock implemented with static member objects , the code looks like this:Modify the Mythread.java class as follows

Package Com.clark.thread;public class MyThread implements Runnable{private int Threadid;private static Object object = New Object lock public MyThread (int id) {This.threadid = id) used for contention between threads; @Overridepublic  void Run () {<strong>/** * passes a reference to the object object to the lock member variable of each thread's objects * so that each thread's lock member points to the same object object * This allows the thread to compete for this unique shared object lock for synchronization. */</strong>synchronized (object) {for (int i = 0; i <; i++) {if (i% ==0) {System.out.println ();} System.out.print ("Thread ID:" +this.threadid+ ":" +i+ "");}}}}
The results are as follows:

Take a look at the first piece of code, add the instance method sychronized the keyword blocked is This object itself, and adding it in a static method sychronized the keyword block is the class itself. static methods are shared by all class instance objects, so thread objects are mutually exclusive access to this static method, allowing for thread synchronization, as shown in the following code:

Package Com.clark.thread;public class MyThread implements Runnable{private int threadid;public MyThread (int id) { This.threadid = ID;} @Overridepublic  void Run () {start (this.threadid);} private static synchronized void start (int threadId2) {for (int i = 0; i <; i++) {if (i% = = 0) {System.out.printl n ();} System.out.print ("Thread ID:" +threadid2+ ":" +i+ "");}}}

The results are as follows =========

thread ID:0:0 Thread id:0:1 thread id:0:2 thread id:0:3 thread id:0:4 thread id:0:5 thread id:0:6 thread id:0:7 thread id:0:8 thread ID: 0:9 thread id:0:10 thread id:0:11 thread id:0:12 thread id:0:13 thread id:0:14 thread id:0:15 thread id:0:16 thread id:0:1 7 thread id:0:18 thread id:0:19 thread id:0:20 thread id:0:21 thread id:0:22 thread id:0:23 thread id:0:24 thread id:0:25 Thread id:0:26 thread id:0:27 thread id:0:28 thread id:0:29 thread id:0:30 thread id:0:31 thread id:0:32 thread id:0:33 Th Read id:0:34 thread id:0:35 thread id:0:36 thread id:0:37 thread id:0:38 thread id:0:39 thread id:0:40 thread id:0:41 thre Ad id:0:42 thread id:0:43 thread id:0:44 thread id:0:45 thread id:0:46 thread id:0:47 thread id:0:48 thread id:0:49 thread ID:0:50 thread id:0:51 thread id:0:52 thread id:0:53 thread id:0:54 thread id:0:55 thread id:0:56 thread id:0:57 thread I d:0:58 Thread id:0:59








Multithreading synchronization problem with synchronized keyword in Java

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.