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?
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?
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
A 7
A 8
A 10
C 9
B 8
B 7
B 10你也许要运行好多次才会出现差异,这就是随机的含义^_^
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