目标是建立三个线程 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++; } }
有两个问题。
第一:获取哪个对象的锁。都只能对那个对象wait和notify。你现在通过synchronized获得的是testThSeq.class的锁。(synchronized一个方法,获取的是方法所属对象的锁,synchronized一个static方法,获取的是方法所属类的class的锁)所以你不能Thread.currentThread().wait();应该testThSeq.class.wait()。notifyAll也一样。
第二:notifyAll紧跟着wait后面,并且都在条件判断state!=wantedState里面,必将产生死锁。线程要么state!=wantedState为true,进入wait等待。要么state!=wantedState为false。永远无法执行到notifyAll这条语句。
改为:
[code="java"]
while (state != wantedState) {
testThSeq.class.wait();
}
testThSeq.class.notifyAll();
[/code]