【发布时间】:2014-07-23 13:44:09
【问题描述】:
我正在尝试同步三个线程以打印 012012012012.... 但它无法正常工作。每个线程都分配有一个编号,当它从主线程接收到信号时会打印该编号。以下程序有问题,我无法捕捉到。
public class Application {
public static void main(String[] args) {
int totalThreads = 3;
Thread[] threads = new Thread[totalThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new MyThread(i);
threads[i].start();
}
int threadIndex = 0;
while (true) {
synchronized(threads[threadIndex]) {
threads[threadIndex].notify();
}
threadIndex++;
if (threadIndex == totalThreads) {
threadIndex = 0;
}
}
}
}
class MyThread extends Thread {
private int i;
public MyThread(int i) {
this.i = i;
}
@Override
public void run() {
while (true) {
synchronized(this) {
waitForSignal();
System.out.println(i);
}
}
}
private void waitForSignal() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
请定义什么是“有问题”...
-
它没有按要求的顺序打印数字。对于其中一次运行,它打印了 01212012102....
-
您没有在非实例信号量上进行同步。例如尝试使用静态成员变量
-
因为这感觉有点像家庭作业,所以在提出解决方案时我们应该遵守哪些规则?
-
不,没有规则。
标签: java multithreading thread-synchronization