/*
多线程实例
买卖商品,生产一个,消费一个
*/
import java.util.concurrent.locks.*;
class Goods
{
private String name;
private int count = 0;//定义一个计数器
private Lock lock = new ReentrantLock();//创建一个锁的对象
private Condition condition_pro = lock.newCondition();//通过锁,创建一个具备等待唤醒功能的Conditionde的实例对象,一个锁可以对应多个Conditionde的实例对象
private Condition condition_con = lock.newCondition();
private boolean flag = false;
public void set(String name)throws InterruptedException
{
lock.lock();//获取锁
try
{
//判断标记,如果为true,生产者等待同时唤醒消费者
while(flag)
condition_pro.await();
this.name = name;
System.out.println(Thread.currentThread().getName()+"..........生产者.."+this.name+":"+(++count));
flag = true;//改变标记
condition_con.signal();//唤醒消费者
}
finally
{
lock.unlock();//释放锁
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
//判断标记,如果为false,消费者等待同时唤醒生产者
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name+":"+count);
flag = false;
condition_pro.signal();//唤醒生产者
}
finally
{
lock.unlock();
}
}
}
class Input implements Runnable
{
private Goods g;
Input(Goods g)
{
this.g = g;
}
public void run()
{
while(true)
{
try
{
g.set("商品");
}
catch (InterruptedException e1)
{
}
}
}
}
class Output implements Runnable
{
private Goods g;
Output(Goods g)
{
this.g = g;
}
public void run()
{
while(true)
{
try
{
g.out();
}
catch (InterruptedException e2)
{
}
}
}
}
class ThreadTest1
{
public static void main(String[] args)
{
Goods g = new Goods();
//创建四个线程
Input in1 = new Input(g);
Input in2 = new Input(g);
Output out1 = new Output(g);
Output out2 = new Output(g);
//启动运行线程
new Thread(in1).start();
new Thread(in2).start();
new Thread(out1).start();
new Thread(out2).start();
}
} |
|