目标是建立三个线程 th1,th2,th3,希望其能按照顺序th1->th2->th3的顺序执行。
下面贴出我的代码,运行时总是不能得到正确的结果,求大神指点~~~~
package threadSeq; public class testThSeq { public volatile static int state = 1; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Thread th1 = new Thread(new Runnable() { public void run() { try { increaseAndNotifyAll(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Thread th2 = new Thread(new Runnable() { public void run() { try { increaseAndNotifyAll(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Thread th3 = new Thread(new Runnable() { public void run() { try { increaseAndNotifyAll(3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); th3.start(); th2.start(); th1.start(); } public synchronized static void increaseAndNotifyAll(int wantedState) throws InterruptedException { System.out.println("state:"+state+";"+Thread.currentThread()+wantedState); while(state!=wantedState){ Thread.currentThread().wait(); Thread.currentThread().notifyAll(); } System.out.println(Thread.currentThread() + " finished"); state++; } }