package com.itheima.thread.demo;
public class ProductDemo {
/**
* @param args
*/
public static void main(String[] args) {
Resource res=new Resource();
Producter pd=new Producter(res);
Consumer cos=new Consumer(res);
Thread t1=new Thread(pd);
Thread t2=new Thread(pd);
Thread t3=new Thread(cos);
Thread t4=new Thread(cos);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int count=1;
private static boolean flag=false;
//生产
public synchronized void set(String name){
while(flag){
try {
this.wait();
} catch (Exception e) {
// TODO: handle exception
}
this.name=name+"..."+count++; //烤鸭1、烤鸭2、烤鸭3
System.out.print(Thread.currentThread().getName()+"......生产者.."+this.name);
flag=true;
notifyAll(); //唤醒所有等待的线程
}
}
//消费
public synchronized void Out (){
if(!flag)
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
System.out.print(Thread.currentThread().getName()+"......消费者..."+this.name);
flag=false;
notifyAll();
}
}
class Producter implements Runnable{
private Resource res;
Producter(Resource res){
this.res=res;
}
@Override
public void run() {
while(true){
res.set("北京烤鸭");
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res=res;
}
@Override
public void run() {
while(true){
res.Out();
}
}
}
各位大侠麻烦帮忙看一下,我看着视频敲的,也不知道哪里出了问题,多线程执行控制台没有反应,也不报错??谢谢! |
|