本帖最后由 碎流 于 2014-9-15 19:00 编辑
package cn.fuxi12;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//新特性生产者消费者
class ziYuanb
{
private String name;
private int jiShu = 0;
private boolean bl = false;
private Lock lock = new ReentrantLock();
private Condition sheng = lock.newCondition();
private Condition xiao = lock.newCondition();
public void shengc(String name)throws InterruptedException
{
lock.lock();
try
{
while(bl)
sheng.await(); //1 2
this.name = name+".."+jiShu++;
System.out.println(Thread.currentThread().getName()+",,,,,,,生产者"+this.name+jiShu);
bl = true;
sheng.signal();
}
finally
{
lock.unlock();
}
}
public void xiaoc() throws InterruptedException
{
lock.lock();
try
{
while(!bl)
xiao.await(); //3
System.out.println(Thread.currentThread().getName()+".....消费者"+this.name+jiShu);
bl = false;
xiao.signal();
}
finally
{
lock.unlock();
}
}
}
class shengChanZhe implements Runnable
{
private ziYuanb zy;
shengChanZhe(ziYuanb zy)
{
this.zy = zy;
}
public void run()
{
while(true)
{
try
{
zy.shengc("+煎饼果子");
} catch (InterruptedException e)
{
}
}
}
}
class xiaoFeiZhe implements Runnable
{
private ziYuanb zy;
xiaoFeiZhe(ziYuanb zy)
{
this.zy = zy;
}
public void run()
{
while(true)
{
try {
zy.xiaoc();
} catch (InterruptedException e) {
}
}
}
}
public class Demo06 {
public static void main(String[] args) {
ziYuanb zy = new ziYuanb();
shengChanZhe sh = new shengChanZhe(zy);
xiaoFeiZhe xf = new xiaoFeiZhe(zy);
Thread t1 = new Thread(sh);
Thread t2 = new Thread(sh);
Thread t3 = new Thread(xf);
Thread t4 = new Thread(xf);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
本来是自己写的,眼看改的都和毕老师一样了,还是不知道哪里出问题,,,,,输出都会卡住,,,像是死锁,,,,想了两个多小时,实在不知道怎么搞,求指点.....或许可能就是很小的问题,但是就是解决不了..
|