Java 为什么不打印计数值?
我有一门主要课程:Java 为什么不打印计数值?,java,multithreading,Java,Multithreading,我有一门主要课程: public class Main { public static void main(String[] args) { Processor p=new Processor(); Thread t1=new Thread() { @Override public void run() { try { p.produce
public class Main {
public static void main(String[] args) {
Processor p=new Processor();
Thread t1=new Thread() {
@Override
public void run() {
try {
p.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
Thread t2=new Thread() {
@Override
public void run() {
try {
p.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("count : "+p.count);
}
}
及
公共类处理器{
队列q=新的LinkedList();
整数计数=0;
public void product()引发InterruptedException{
已同步(此){
对于(inti=1;i在这一行:
t2.join();
您正在等待一个线程,该线程由于consume
方法中的while(true)
循环而永远不会终止。您的consume方法中有一个while(true)。您需要中断该线程或添加更好的条件
t2.join();