本文为生产者与消费者的实例,不过规定为:生产一个商品,消费一个商品。生产一个,消费一个...... 如此
代码如下:
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
/**
* Created by patkritLee on 2017/1/5.
*/
public class ProducerConsumerDemo {
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(con);
t1.start();
t2.start();
}
}
class Resource{
private String name;
private int cnt = 1;
private boolean flag = false;
public synchronized void set(String name){
if(flag){
try{
this.wait();
}catch (Exception e){}
}
this.name = name+"--"+cnt++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag = true;
this.notify();
}
public synchronized void out(){
if(!flag){
try{
wait();
}catch (Exception e){}
}
System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);
flag = false;
this.notify();
}
}
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();
}
}
}
部分输出代码如下:
Thread-0...生产者...+商品+--243572
Thread-1...消费者......+商品+--243572
Thread-0...生产者...+商品+--243573
Thread-1...消费者......+商品+--243573
Thread-0...生产者...+商品+--243574
Thread-1...消费者......+商品+--243574
Thread-0...生产者...+商品+--243575
Thread-1...消费者......+商品+--243575
Thread-0...生产者...+商品+--243576
Thread-1...消费者......+商品+--243576
Thread-0...生产者...+商品+--243577
Thread-1...消费者......+商品+--243577
Thread-0...生产者...+商品+--243578
Thread-1...消费者......+商品+--243578
Thread-0...生产者...+商品+--243579
Thread-1...消费者......+商品+--243579
Thread-0...生产者...+商品+--243580
Thread-1...消费者......+商品+--243580
Thread-0...生产者...+商品+--243581
Thread-1...消费者......+商品+--243581