jdk5提供了將同步synchronized替換成了現實Lock操作。將Object中的wait,notify,notifyAll,替換了Condition對象,該實例實現了本方喚醒對方操作
代碼如下:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 生產消費者問題
*
* jdk 1.5之後提供了多線程升級解決方案
*
* 1.將同步synchronized替換成 lock操作
* 2.將Object中的wait(),notify(),notifyAll()替換成了Condition該對象可以用lock來得到
* 3.該實例中實現了本方喚醒對方操作
*
* @author Yxx
*
*/
public class ConditionThread2 {
public static void main(String agrs[]){
Res3 r = new Res3();
Producer1 p = new Producer1(r);
Consumer1 c = new Consumer1(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
Thread t3 = new Thread(p);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/**
* 資源
* @author Yxx
*
*/
class Res3{
private String name;
boolean flag = false;
ReentrantLock lock = new ReentrantLock();
private Condition con1 = lock.newCondition();
private Condition con2 = lock.newCondition();
public void set(String name)throws IllegalMonitorStateException{
lock.lock(); //得到同步鎖
try{
while(flag)
try {
con1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name = name;
System.out.println("生產者生產了商品--------------->"+this.name);
flag = true;
con2.signal();
}finally{
lock.unlock();//釋放解鎖
}
}
public void out(){
lock.lock(); //得到同步鎖
try{
while(!flag)
con2.await();
System.out.println("消費者消費了商品-------------------------------------------->"+this.name);
flag = false;
con1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock(); //釋放解鎖
}
}
}
/**
* 生產者
* @author Yxx
*
*/
class Producer1 implements Runnable{
Res3 r;
public Producer1(Res3 r){
this.r = r;
}
public void run() {
while(true){
r.set("商品");
}
}
}
class Consumer1 implements Runnable{
Res3 r;
public Consumer1(Res3 r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}