生产者消费者问题

public class Main { 

public static void main(String[] args){

XClass x = new XClass();

ProduceX prodx = new ProduceX(x);

PrintX printx = new PrintX(x);

prodx.start();

printx.start();

}

}

class XClass {

private int x;

private boolean produced = false;

public XClass(){

this.x = 0;

}

public synchronized int modifyX(){

while(produced==true){

try{

wait();

}

catch(InterruptedException ie){}

}

x=x+1;

produced = true;

notifyAll();

return x;

}

public synchronized void printX(){

while(produced==false){

try{

wait();

}

catch(InterruptedException ie){}

}

produced = false;

System.out.println(Thread.currentThread().getName()+" prints "+x);

notifyAll();

}

}

class PrintX extends Thread{

private XClass x;

public PrintX(XClass x){

this.x = x;

}

public void printX(){

for(int i=0;i<10;i++){

x.printX();

}

}

}

class ProduceX extends Thread{

private XClass x;

public ProduceX(XClass x){

this.x = x;

}

public void run(){

for(int i=0;i<10;i++){

x.modifyX();

System.out.println(Thread.currentThread().getName()+" increases x to "+ x.modifyX());

}

}

}

该问题类似于生产者消费者。这里的producex会将x增加1,并且会再次增加,直到x被printx打印。但是,似乎没有结果。错误在哪里?生产者消费者问题

回答:

PrintX没有run()方法。没有什么可以做的。

以上是 生产者消费者问题 的全部内容, 来源链接: utcz.com/qa/266407.html

回到顶部