123, the design of 4 threads, of which two threads each time to J 1, another two threads to j each reduction of 1. Write the program.
The following procedure uses the Inner class implementation thread, and does not consider the order problem when adding or subtracting the J.
public class threadtest1{ private int J; public static void Main (String args[]) { ThreadTest1 tt=new ThreadTest1 (); Inc Inc=tt.new Inc. (); Dec dec=tt.new Dec (); for (int i=0;i<2;i++) { Thread T=new Thread (inc); T.start (); T=new Thread (DEC); T.start (); } } Private synchronized Void Inc () { j + +; System.out.println (Thread.CurrentThread (). GetName () + "-inc:" +j); } private synchronized void Dec () { j--; System.out.println (Thread.CurrentThread (). GetName () + "-dec:" +j); } Class INC implements runnable{ public void Run () { for (int i=0;i<100;i++) { Inc. (); } } } Class Dec implements runnable{ public void Run () { for (int i=0;i<100;i++) { Dec (); } } } } |