认为共享对象 Control
将强制执行 n
线程(Number
)依次显示,他们显然没有。
数字:
public class Number implements Runnable {
private int i_;
private Control control;
public Number(int i, Control c) {
i_ = i;
control = c;
}
public void start() {
new Thread(this).start();
}
public void run() {
synchronized(control) {
control.call(i_);
}
}
}
控制:
public class Control {
private int i_ = 0;
public void call(int i) {
if(i != i_) {
try {
wait();
}
catch(Exception e) {}
}
System.out.println(i);
i_++; // next, please
notify();
}
}
测试线束(主)。
public class RunNumbers {
public static void main(String args[]) {
int n = 0;
if (args.length > 0) {
n = Integer.parseInt(args[0]);
}
Control c = new Control();
for(int i = 0; i < n; ++i) {
new Number(i, c).start();
}
}
}
有什么想法吗?
以上是通过拼凑几个只涉及一对线程的教程得出的(不知道是怎么回事)------导致无法将所有的东西扩展到两个以上的线程。
经过一番研究,可以通过修改以下两行来解决上述问题 Control.java
:
(a) 改变 if(i != i_) {
到 while(i != i_) {
(b) 改变 notify();
到 notifyAll();