A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘文飞 中级黑马   /  2012-11-17 19:14  /  1623 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 刘文飞 于 2012-11-17 21:05 编辑

import java.util.concurrent.locks.*;
class Resource{
private int count;
private boolean flag;
private Lock lock = new ReentrantLock();
private Condition condition_pro = new lock.newCondition();//多了个new
private Condition condition_con = new lock.newCondition();
public void produce() throws InterruptedException
{
  lock.lock();
  try{
   while(flag)
   {
    condition_pro.await();
   }
   System.out.println(Thread.currentThread().getName() + "---生产---" + ++count );
   flag = true;
   condition_con.signal();
  }
  finally
  {
   lock.unlock();
  }
}
public void consume() throws InterruptedException
{
  lock.lock();
  try
  {
   while(!flag)
   {
    condition_con.await();
   }
   System.out.println(Thread.currentThread().getName() + "---消费---" + count--);
   flag = false;
   condition_pro.signal();
  }
  finally
  {
   lock.unlock();
  }
}
}
class Producer implements Runnable
{
private Resource res;
public Producer(Resource res)
{
  this.res = res;
}
public void run()
{
  while(true)
  {
   try
   {
    res.produce();
   }
   catch(InterruptedException e)
   {
    e.printStackTrace();
   }
  }
}
}
class Consumer implements Runnable
{
private Resource res;
public Consumer(Resource res)
{
  this.res = res;
}
public void run()
{
  while(true)
  {
   try
   {
    res.consume();
   }
   catch(InterruptedException e)
   {
    e.printStackTrace();
   }
  }
}
}
public class ProducerConsumerLockDemo
{
public static void main(String[] args)
{
  Resource res = new Resource();
  Producer pro = new Producer(res);
  Consumer con = new Consumer(res);
  Thread t1 = new Thread(pro);
  Thread t2 = new Thread(pro);
  Thread t3 = new Thread(pro);
  Thread t4 = new Thread(con);
  Thread t5 = new Thread(con);
  Thread t6 = new Thread(con);
  Thread t7 = new Thread(con);
  t1.start();
  t2.start();
  t3.start();
  t4.start();
  t5.start();
}
}

点评

你是在自娱自乐 。  发表于 2012-11-18 00:21

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马