标签:多线程
多线程生产者只有多个生产者,多个消费者!这里不讲基础的知识。代码如下
package Thread;
class Resource {
private String name;
private int count=0;
private boolean flag=false;
public synchronized void set(String name){
while (flag){ //这里必须用循环因为要让每个生产者都知道自己要不要生产。如果不加就可能出现生产者唤醒生产者,然后连续两次生产。
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag=true;
this.notifyAll();//这里也要用notifyAll()否则,可能造成所有的线程都在等待。
}
public synchronized void out(){
while(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable{
private Resource res;
Producer(Resource res){
this.res=res;
}
public void run() {
while(true){
res.set("商品");
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res=res;
}
public void run() {
while(true){
res.out();
}
}
}
public class ProducterConsumerDemo {
public static void main(String[] args) {
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(pro);
Thread t3=new Thread(con);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
这是运行的结果。可以看出都是一个生产一个消费。
标签:多线程
原文地址:http://blog.51cto.com/ji123/2084201