import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 线程间通信--生产者消费者.JDK 升级5.0版本。
*【【Lock】】
*提供了多线程升级解决方案,
*将同步synchronized替换成实现Lock操作
*将Object中的wait,notify,notifyAll,替换成了Condition 对象
*该对象可以Lock锁,进行获取
*该示例中,实现了本方只唤醒对方的操作。
*/
public class D_Th_Lock {
public static void main(String []args){
Resource1 r=new Resource1();
new Thread(new Shengc1(r)).start();
new Thread(new Shengc1(r)).start();
new Thread(new Xiaof1(r)).start();
new Thread(new Xiaof1(r)).start();
/*
Shengc sc=new Shengc(r);
Xiaof xf=new Xiaof(r);
Thread t1=new Thread(sc);
Thread t2=new Thread(xf);
Thread t3=new Thread(sc);
Thread t4=new Thread(xf);
t1.start();
t2.start();
t3.start();
t4.start();
*/
}
}
class Resource1{
private String name;
private int count=1;
private boolean falg=false;
private Lock lock=new ReentrantLock();
private Condition condition_s=lock.newCondition();
private Condition condition_x=lock.newCondition(); //创建2个锁对象。
public void set(String name) throws InterruptedException{
lock.lock();//获取锁 加上锁
try{
while(falg)
condition_s.await();//t1 t2 己方躺下
this.name=name+"..."+count++;
System.out.println(Thread.currentThread().getName()+"..生产.."+this.name);
this.falg=true;
condition_x.signal();//唤醒 t3、t4其中一个
}
finally{
lock.unlock(); 不论如何都释放锁。
}
}
public void get()throws InterruptedException{
lock.lock();
try{
while(!falg)
condition_x.await();//t3 t4 己方躺下
System.out.println(Thread.currentThread().getName()+"-----消费----"+this.name);
this.falg=false;
condition_s.signal();//唤醒 t1、t2其中一个
}
finally{
lock.unlock();
}
}
}
class Shengc1 implements Runnable{
private Resource1 r;
Shengc1(Resource1 r){
this.r=r;
}
public void run(){
int x=0;
while(true){
try {
r.set("+商品+");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("出现异常");
}
}
}
}
class Xiaof1 implements Runnable{
private Resource1 r;
Xiaof1(Resource1 r){
this.r=r;
}
public void run(){
while(true){
try {
r.get();
} catch (InterruptedException e) {
System.out.println("出现异常222222");
e.printStackTrace();
}
}
}
}
lock 更灵活的实现并扩展了synchronized的功能。
黑马官网: http://edu.csdn.net/heima