多執行緒經典——生產者消費者問題(加鎖版)
阿新 • • 發佈:2019-02-19
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 生產者,消費者
* Lock介面:出現替代了同步程式碼塊或者同步函式,將同步的隱式鎖操作變成現實鎖操作,
* 同時更加靈活,可以一個鎖上加多組監視器。
* lock()獲取鎖
* unlock()釋放鎖,通常定義在finally程式碼塊中
* Condition介面:出現替代了Object中的wait notify notifyAll方法
* 將這些監視器方法單獨進行了封裝,變成Condition監視器物件。可以任意鎖進行組合
* await() signal() signalAll()
*
* */
class Resrouce
{
private String name;
private int count=1;
private boolean flag=false;
//建立一個鎖物件
Lock lock=new ReentrantLock();
//通過已有的鎖獲取該鎖上的監視器物件
// Condition con=lock.newCondition();
//通過已有的梭獲取兩組監視器,一組監視生產者,一組監視消費者
Condition producer_con=lock.newCondition();
Condition consumer_con=lock .newCondition();
public void set(String name)
{
lock.lock();
try
{
while(flag)
try{producer_con.await();}
catch(InterruptedException e)
{}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"..生產者." +this.name);
flag=true;
consumer_con.signal();
}
finally
{
lock.unlock();
}
}
public void out()
{
lock.lock();
try
{
while(!flag)
try{consumer_con.await();}
catch(InterruptedException e)
{}
System.out.println(Thread.currentThread().getName()+"..消費者............."+this.name);
flag=false;
producer_con.signal();
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Resrouce r;
Producer(Resrouce r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("烤鴨");
}
}
}
class Consumer implements Runnable
{
private Resrouce r;
Consumer(Resrouce r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
public class Demo
{
public static void main(String[] args)
{
Resrouce r=new Resrouce();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
Thread t3=new Thread(pro);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}