这个程序运行到无限循环:
public class NewClass {
static void execute(String[] tasks) {
PCTest test = new PCTest(tasks);
new Thread(test.producer, "Prod").start();
new Thread(test.consumer, "Con").start();
}
private static class PCTest {
private String currentTask;
final String[] producerTasks;
final Prod producer;
final Consmr consumer;
public PCTest(String[] producerTasks) {
this.producerTasks = producerTasks;
producer = new Prod();
consumer = new Consmr();
}
private class Prod implements Runnable {
Prod() {
}
public synchronized void run() {
int i = 0;
while (i < producerTasks.length) {
if (currentTask == null) {
currentTask = producerTasks[i++];
this.notify();
}
try {
this.wait();
} catch (InterruptedException e) {
//do Nothing
}
}
}
}
private class Consmr implements Runnable {
Consmr() {
}
public synchronized void run() {
int i = 0;
while (i < producerTasks.length) {
if (currentTask != null) {
System.out.print(currentTask);
i++;
if (i < producerTasks.length) {
System.out.print(",");
}
currentTask = null; //*
this.notify();
}
try {
this.wait();
} catch (InterruptedException e) {
//do Nothing
}
}
}
}
}
public static void main(String a[]){
String ar[]={"a","b","c"};
execute(ar);
}
}
答案 0 :(得分:1)
从上面的代码中,您的线程似乎处于inifinite wait
状态。
因为wait()和notify()没有正确完成。
您的Producer线程将设置currentTask
并通过调用this.wait()
来等待。这里this
是Prod
类的实例。您的消费者实际上是this.notify()
,但此处this
是Consmr
类的实例,您的消费者也会进入inifinite wait
州。
只是你不是notifying
另一个帖子waiting
上的实例
希望现在明白。
答案 1 :(得分:0)
如果从
更改两个调用,它将停止无限循环this.wait()
到
this.wait(50)
但这几乎是一个黑客攻击。