黑马程序员技术交流社区
标题:
基础学习day12多线程2消费者生产者
[打印本页]
作者:
不怕黑人
时间:
2015-7-22 22:17
标题:
基础学习day12多线程2消费者生产者
public class Day12Test1 {
public static void main(String[] args) {
Resouce r = new Resouce();
new Thread(new Producer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
}
}
class Resouce{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name){
while(flag)
try{
wait();
}
catch(Exception e){
// throw new RuntimeException();
}
this.name = name + count++;
System.out.println(Thread.currentThread().getName()+"...生产者......"+this.name);
flag = true;
notifyAll();
}
public synchronized void out(){
while(!flag)
try{
wait();
}
catch(Exception e){
// throw new RuntimeException();
}
System.out.println(Thread.currentThread().getName()+"+消费者+"+this.name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable{
private Resouce r;
Producer(Resouce r){
this.r = r;
}
public void run(){
while(true){
r.set("汉堡");
}
}
}
class Consumer implements Runnable{
private Resouce r;
Consumer(Resouce r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2