Here is a small program to illustrate that the logic is a counter (int i), the main logical function is that if the synchronization monitoring resource I, then I do not output the value, but if the keyword synchronized is not added, because it is two threads concurrently executed, so will output the value of I, class implements the Runnable interface.
The following is the run () method, using I once plus two, if the odd output, if the output (then concurrent programming, the shared resources are not monitored), if there is no output (the shared resources are monitored, only one thread is allowed to use at a time), the Runnable interface's Run method is as follows:
Public voidrun () { while(true){ if( This. GetValue ()%2!=0) {System.out.println ( This. GetValue ()); } if(Thread.CurrentThread (). GetName (). Equals ("B")){ This. Next (); } Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }
Write a method to get I value, and add the method of I value, if the concurrent monitor concurrency thread to add synchronized, if not can not add, self-comparison results:
Public synchronized void // the synchronized here defines the code block here, allowing only one thread to access i+=2; // I add two at once public synchronized int GetValue () {return i; } // The value of I is obtained, and the output is judged
Create a Main method in the class, construct an object, instantiate two threads, add a bit, synchronized the keyword-decorated code block, allow only a different thread of the same object to access at most one time, and if two objects are constructed, then the synchronized decorated block of code, will still be accessed at the same time, prone to data chaos, deadlock phenomenon.
The code is as follows:
Public Static voidMain (string[] args) {Secondthread St=NewSecondthread (); Thread St1=NewThread (St, "a"); Thread St2=NewThread (St, "B"); St1.start (); St2.start (); Try{st1.join (); St1.join (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }
Output is (no output, and thread does not destroy):
If you get rid of synchronized, you can output odd numbers.
Java Concurrency Programming example (synchronized)