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();
}
}
}