### java 在1.5之后提供了多線程升級解決方案
其中Synchronized被接口Lock所代替
Object中的wait notify notifyAll被 Condition接口中的方法所替代。
Lock類的介紹:----其中,Lock 替代了 synchronized 方法和語句的使用
lock:獲取鎖
unlock:釋放鎖
newCondition:返回Condition實例
Condition類的介紹:----Condition 替代了 Object 監視器方法的使用
await() 是線程等待,類似于wait方法。需要拋
signal() 喚醒一個等待的線程
signalAll() 喚醒所有等待的線程
### 本例主要演示生產者、消費者這個經典案例的替換方案。
并學習Lock和Condition的方法
描述:生產者負責生產商品,消費者負責消費商品,其中生產者為空時不能,消費者不能進行消費。
實現步驟:
1、定義一個操作類方法:Resources類,屬性:name,商品編號 count.標志 flag.
當flag為false時,表示生產者還未生成,這是需要執行生成方法。執行完后將flag設置為true。
并喚醒消費者去執行消費方法
?當flag為true時,表示生產者已經生產一個產品,執行等待(await)操作。此時,消費者執行完消
費操作之后,將flag設置為false,并喚醒生產者執行生產方法。
void set(String name)方法,void out();方法。
2、生產者類:Producer實現Runnable接口,覆寫run方法。Producer(Resources res),有參構造方法
3、消費者類:Consumer實現Runnabel接口,覆寫run方法。Consumer(Resources res),有參構造方法
4、創建多個生產者、消費這線程。用來啟動多線程
~~~
import java.util.concurrent.locks.*;
public class ProducerConsumer{
public static void main(String args[]){
Resources res = new Resources();
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); //生產者..
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class Resources{
private String name;
private int count=1;
private boolean flag;
private final Lock lock = new ReentrantLock(); //創建一個Lock的實例
private Condition condition_Pro = lock.newCondition(); //創建一個控制Producer線程的Condition實例
private Condition condition_Con = lock.newCondition();//創建一個控制Consumer線程的condition實例
public void set(String name)throws InterruptedException{
lock.lock(); //開啟鎖
try{
while(flag) //需要持續判斷鎖,如果為true,需要等待
condition_Pro.await(); //Producer線程等待。
this.name = name+"--"+(++count);
System.out.println(Thread.currentThread().getName()+"...生產者..."+this.name);
flag = true;
condition_Con.signal(); //喚醒Customer的線程
}finally{
lock.unlock(); //無論程序是否執行完,都要釋放資源
}
}
public void out()throws InterruptedException{
lock.lock();
try{
while(!flag) //當flag為false時,沒有生成,消費者需要等待
condition_Con.await(); //消費者線程等待
System.out.println(Thread.currentThread().getName()+".......消費者........."+count);
flag = false;
condition_Pro.signal(); //喚醒Producer的線程
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
Resources res;
public Producer(Resources res){
this.res = res;
}
public void run(){
//重復執行生產的方法
try{
while(true)
res.set("lzl");
}catch(InterruptedException e){}
}
}
class Consumer implements Runnable{
Resources res;
public Consumer(Resources res){
this.res = res;
}
public void run(){
//重復執行消費的方法
try{
while(true)
res.out();
}catch(InterruptedException e){}
}
}
~~~