是我不认真吗?为什么跟毕老师上的视频上讲的一模一样,为什么我的运行不出来结果?
生产者和消费者问题,生产一个,消费一个
package Thread;
class Resource {
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name){
if(flag){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
this.name = name + count;
count++;
// 打印生产了那件商品
System.out.println(Thread.currentThread().getName()+"......生产者...."+this.name);
flag=true;
this.notify();//唤醒消费者
}
}
public synchronized void out(){
if(!flag){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+count);
flag=false;
//唤醒生产者
this.notify();
}
}
}
//生产者类
class Producer implements Runnable{
private Resource r;
public Producer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.set("馒头");
}
}
}
// 消费者类
class Consumer implements Runnable {
private Resource r;
public Consumer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}
public class ThreadTest3 {
public static void main(String[] args) {
Resource r=new Resource();
Producer p=new Producer(r);
Consumer c=new Consumer(r);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.start();
t2.start();
}
}
|
|