Java code
PackageCom.yx.zzg; Public classThreadTest1 {Private intJ; Public Static voidMain (String args[]) {ThreadTest1 TT=NewThreadTest1 (); INC Inc= TT.NewInc (); Dec Dec= TT.NewDec (); for(inti = 0; I < 2; i++) {Thread T=NewThread (INC); T.start (); T=NewThread (DEC); T.start (); } } Private synchronized voidInc () {J++; System.out.println (Thread.CurrentThread (). GetName ()+ "-inc:" +j); } Private synchronized voidDec () {J--; System.out.println (Thread.CurrentThread (). GetName ()+ "-dec:" +j); } classIncImplementsRunnable { Public voidrun () { for(inti = 0; I < 100; i++) {Inc (); } } } classDecImplementsRunnable { Public voidrun () { for(inti = 0; I < 100; i++) {Dec (); } } }}
Note: Here the INC method and the Dec method plus the Synchronized keyword is because when two threads operate the same variable at the same time, even if the simple J + + operation, at the bottom of the system is also through a number of machine statements, so it is time to execute the J + + process, it is possible to execute J + +, another thread H will operate on J, so another thread h might not be able to manipulate the most recent value. Therefore, you provide thread synchronization.
Version 2:
This version does not require synchronized, and Atomicinteger instead
PackageCom.yx.zzg; Public classThreadTest1 {private Atomicinteger j=new atomicinteger (); Public Static voidMain (String args[]) {ThreadTest1 TT=NewThreadTest1 (); INC Inc= TT.NewInc (); Dec Dec= TT.NewDec (); for(inti = 0; I < 2; i++) {Thread T=NewThread (INC); T.start (); T=NewThread (DEC); T.start (); } } Private synchronized voidInc () {j.incrementandget ();System.out.println (Thread.CurrentThread (). GetName ()+ "-inc:" +j); } Private synchronized voidDec () {j.decrementandget ();System.out.println (Thread.CurrentThread (). GetName ()+ "-dec:" +j); } classIncImplementsRunnable { Public voidrun () { for(inti = 0; I < 100; i++) {Inc (); } } } classDecImplementsRunnable { Public voidrun () { for(inti = 0; I < 100; i++) {Dec (); } } }}
Design 4 threads, where two threads add 1 to J at a time, and two threads each decrease by 1 for j