class Resource
{
private String name;
private int count=1;
private boolean flag=false;
//Lock 替代了 synchronized 方法和语句的使用
private Lock lock = new ReentrantLock();
//Condition 替代了 Object 监视器方法的使用
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name)throws InterruptedException
{
//获取锁
lock.lock();
try
{
while(flag)
condition_pro.await();
this.name=name+count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag=true;
condition_con.signal();
}
finally
{
//释放锁
lock.unlock();//释放锁的动作一定要执行
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+".消费者."+this.name);
flag=false;
condition_pro.signal();
}
finally
{
lock.unlock();
}
}
}
class Produser implements Runnable
{
private Resource res;
Produser(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
try
{
res.set("商品");
}
catch(InterruptedException e)
{
}
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
try
{
res.out();
}
catch(InterruptedException e)
{
}
}
}
}
public class ProducerConsumerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource r=new Resource();
/*
new Thread(new Produser(r)).start();
new Thread(new Produser(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
我想得到的知识:该程序如何用 void interrupt() 中断线程。 这个方法在代码中怎么使用?谢谢! |
|