1. Description of the problem:
A class has 2 methods Func1 (), Func2 (), a threadcount thread that requires all threads to execute func1 (), and then Func2 ().
2. Analysis: 1) What is the standard of func1 () execution of all threads? 2) How do I share variables between threads? 3. Code implementation 1) source code:
/** * */ PackageCom.sunny.www.interview;ImportJava.util.concurrent.atomic.AtomicInteger;/*** All threads Execute Method 1, then Execute Method 2 *@authorSunny **/ Public classSyn2threadsImplementsRunnable {PrivateAtomicinteger ThreadCount; Publicsyn2threads (Atomicinteger threadcount) {Super(); This. ThreadCount =ThreadCount; } PublicAtomicinteger Getthreadcount () {returnThreadCount; } Public voidSetthreadcount (Atomicinteger threadcount) { This. ThreadCount =ThreadCount; } Private voidfunc1 () {System.out.println (Thread.CurrentThread (). GetName ()+ "Execute func1,threadcount=" +threadcount.decrementandget ()); } Private voidFunc2 () {System.out.println (Thread.CurrentThread (). GetName ()+ "Execute func2,threadcount=" +threadcount); } @Override Public voidrun () {func1 (); synchronized(threadcount) { while(0 <Threadcount.get ()) { Try {System.out.println (Thread.CurrentThread (). GetName () + "func1 not finished totally,threadcount=" + ThreadCount);threadcount.wait (); } Catch(interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName ()+ "Wait Error"); }} threadcount.notifyall (); } func2 (); } Public Static voidMain (string[] args) {intThreadCount = 5; Syn2threads syn2threads=NewSyn2threads (NewAtomicinteger (threadcount)); for(inti = 1; I <= threadcount; i++){ NewThread (Syn2threads, "thread-" +i). Start (); } }}2) Operation effect:
Thread-2 Execute func1,threadcount=4Thread-2 func1 not finished totally,threadcount=3Thread-1 Execute func1,threadcount=3Thread-4 Execute func1,threadcount=2Thread-4 func1 not finished totally,threadcount=2Thread-1 func1 not finished totally,threadcount=2Thread-5 Execute Func1,threadcount=1Thread-5 func1 not finished totally,threadcount=1Thread-3 Execute func1,threadcount=0Thread-3 Execute func2,threadcount=0Thread-5 Execute func2,threadcount=0Thread-1 Execute func2,threadcount=0Thread-4 Execute func2,threadcount=0Thread-2 Execute func2,threadcount=0
Java multi-threaded pen question---All threads func1 () executed, then FUNC2 () implementation