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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李海鹏 中级黑马   /  2013-1-17 19:35  /  1683 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张向辉 于 2013-1-22 11:09 编辑

import java.util.concurrent.locks.*;
public  class Producer7
{
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();
}
}

class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
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();//t1,t2
   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 Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
  this.res = res;
}
public void run()
{
  while(true)
  {
   
   synchronized(res)
   {
    while(res.count ==1000)
    {
    break;
    }
    try
    {
     res.set("+商品+");
    }
    catch (InterruptedException e)
    {
    }
   }
  }
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
  this.res = res;
}
public void run()
{
  while(true)
  {
   
   synchronized(res)
   {
    while(res.count ==1000)
    {
    break;
    }
    try
    {
     res.out();
    }
    catch (InterruptedException e)
    {
    }
   }
  }
}
}
我就是有个想法加了双层锁,多加了synchronized,但是我不知道怎么都解开这两把锁,让程序能够运行,谁能帮我解答?

评分

参与人数 1黑马币 +9 收起 理由
Rancho_Gump + 9 神马都是浮云

查看全部评分

3 个回复

倒序浏览
这运行不起来吧,你两把锁都指向了同一个对象,这不单单是死锁了,你想下一把钥匙开一个锁,但是这个锁里还有个锁,你的钥匙(当前有执行权的线程)能打开吗
回复 使用道具 举报
我只是突发奇想而已,可能真的没有解决办法吧
回复 使用道具 举报
那样会有死锁问题出现的,小几率出现线程之间和谐的状态,开发当中应尽量减少死锁的存在。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马