class Waiting2 implements Runnable {
int state; public synchronized void run() {
if (state++ < 3) {
System.out.print(" " + Thread.currentThread().getId());
try {
this.wait();
} catch (Exception e) {
}
System.out.print(" " + Thread.currentThread().getId());
} else {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
notify();
notifyAll();
}
} public static void main(String[] args) {
Waiting2 w = new Waiting2();
new Thread(w).start();
new Thread(w).start();
new Thread(w).start();
new Thread(w).start();
}
}这里为什么先wait的一定会先notify?

解决方案 »

  1.   

    没有,SUN网站上SCJP考试的自测题,不懂呀。
      

  2.   

    看你的代码,这几个线程优先级相同,当线程wait之后,它会进入一个wait列表,先wait的,当然排在前面,也最先被唤醒.
      

  3.   

    说错了,刚查了一下,wait方法会随机唤醒一个线程,我修改了一下你的程序:
    public class Waiting2 implements Runnable { int state; public synchronized void run() {
    if (state++ < 3) {
    System.out.println(" A " + Thread.currentThread().getId());
    try {
    this.wait();
    } catch (Exception e) {
    }
    System.out.println(" B " + Thread.currentThread().getId());
    } else {
    try {
    System.out.println(" C " + Thread.currentThread().getId());
    Thread.sleep(2000);
    } catch (Exception e) {
    }
    notify();
    notifyAll();
    }
    } public static void main(String[] args) {
    Waiting2 w = new Waiting2();
    new Thread(w).start();
    new Thread(w).start();
    new Thread(w).start();
    new Thread(w).start();
    }
    }这样看的清楚一些.多运行几次,就可以看出效果了.
    这是我运行几次之后得到的一个结果:
     A 8
     A 7
     A 9
     C 10
     B 8
     B 7
     B 9
      

  4.   

    这是SUN网站上SCJP考试的自测题,我没用编译器的时候根本不知道运行结果是这样子的。你能告诉我假如第一次输出“689”接下来一定输出6吗?
      

  5.   

    不会,你把我修改的程序,多输出几次,就知道了.这是我多次运行后得到的另一组数据:
     A 7
     A 8
     A 10
     C 9
     B 8
     B 7
     B 10你也许要运行好多次才会出现差异,这就是随机的含义^_^
      

  6.   

          楼上们说的很对:notify()/notifyAll()方法会随机唤醒一个wait()线程
      

  7.   

    晕了,大家干脆看看这题选什么吧3. class Waiting2 implements Runnable {
    4.   int state;
    5.   public synchronized void run() {
    6.     if (state++ < 3) {
    7.       System.out.print(" " + Thread.currentThread().getId());
    8.       try { this.wait(); } catch (Exception e) { }
    9.       System.out.print(" " + Thread.currentThread().getId());
    10.     }
    11.     else {
    12.       try { Thread.sleep(2000); } catch (Exception e) { }
    13.       notify();
    14.       notifyAll();
    15.     }
    16.   }
    17.   public static void main(String [] args) {
    18.     Waiting2 w = new Waiting2();
    19.     new Thread(w).start();
    20.     new Thread(w).start();
    21.     new Thread(w).start();
    22.     new Thread(w).start();
    23.   }
    24. }Which two results are possible? (Choose two.)6 7 8 9
    6 7 8 6
    6 7 8 6 7 8
    6 7 8 6 7 9
    6 7 8 8 6 7
    6 7 8 6 6 7 8
    6 7 8 9 6 7 8 9