Multi-threaded synchronization
Why to introduce a synchronization mechanism
In a multithreaded environment, there could be two or more threads trying to access a limited resource at the same time. This potential resource conflict must be prevented.
WORKAROUND: Lock the thread when it is using a resource. After the first thread that accesses the resource adds a lock to it, the other thread can no longer use that resource unless it is unlocked.
About member variables and local variables: If a variable is a member variable, then when multiple threads manipulate member variables of the same object, they affect the member variable (that is, a thread
The change of the member variable will affect the other thread).
If a variable is a local variable, then each thread will have a copy of that local variable, and one thread's change to that local variable will not affect other threads.
Member variables
Public classThreadTest { Public Static voidMain (string[] args) {Runnable thread=NewMyThread (); Thread T1=Newthread (thread); Thread T2=Newthread (thread); T1.start (); T2.start (); }}classMyThreadImplementsRunnable {inti; @Override Public voidrun () { while(true) {System.out.println (Thread.CurrentThread (). GetName ()+ "i =" + i++); Try{Thread.Sleep (Long) (Math.random () * 1000)); } Catch(interruptedexception e) {e.printstacktrace (); } if(10 = =i) { Break; } } }}
Run results
Thread-0 i = 0thread-1 i = 1thread-1 i = 2thread-0 i = 3thread-1 i = 4thread- 0 i = 5thread-0 i = 6thread-0 i = 7thread-1 i = 8thread-0 i = 9
Local variables
Public classThreadTest { Public Static voidMain (string[] args) {Runnable thread=NewMyThread (); Thread T1=Newthread (thread); Thread T2=Newthread (thread); T1.start (); T2.start (); }}classMyThreadImplementsRunnable {@Override Public voidrun () {inti = 0; while(true) {System.out.println (Thread.CurrentThread (). GetName ()+ "i =" + i++); Try{Thread.Sleep (Long) (Math.random () * 1000)); } Catch(interruptedexception e) {e.printstacktrace (); } if(10 = =i) { Break; } } }}
Run results
Thread-0 i = 0thread -1 i = 0thread -0 I = 1thread -1 i = 1thread -0 i = 2thread -1 i = 2thread -0 i = 3thread -1 i = 3thread -0 i = 4thread -1 i = 4thread -0 i = 5thread -0 i = 6thread -1 i = 5thread -1 i = 6thread -0 i = 7thread -1 i = 7thread -0 i = 8thread -0 i = 9thread -1 i = 8thread -1 i = 9
Java Multithreading 2: Thread synchronization