本帖最后由 孙传磊 于 2013-3-6 17:59 编辑
下面是 JDK5.0升级版 Lock_Condition机制 下关于 多线程间的通信 代码模式提取,以及自创的 记忆发描述。有不恰当的地方请多多指教。
……
final Lock lock = new ReentrantLock();//买锁
final Condition notFull = lock.newCondition(); //为该锁配把钥匙1
final Condition notEmpty = lock.newCondition(); //为该锁配把钥匙2
……
……
lock.lock();//为门挂上锁
try {
while (…)
notFull.await();//用钥匙1锁门
……
notEmpty.signal();//通知:用钥匙2开锁
} finally {
lock.unlock();//从门上取下锁
}
……
lock.lock();//为门挂上锁
try {
while (…)
notEmpty.await();//用钥匙2锁门
……
notFull.signal();//通知:用钥匙1开锁
} finally {
lock.unlock();//从门上取下锁
}
…
应用举例:生产者与消费者。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Resource {
private String name;
private int count=1;
boolean flag=false;
private Lock lock=new ReentrantLock();
private Condition notFull=lock.newCondition();
private Condition notEmpty =lock.newCondition();
public void set(String name) throws InterruptedException {
lock.lock();
try {
while(flag)
notFull.await();
this.name = name+"^"+count++;
System.out.println(Thread.currentThread().getName()+"*生产者*"+this.name);
flag=true;
notEmpty.signal();
} finally{
lock.unlock();
}
}
public void out() throws InterruptedException {
lock.lock();
try{
while(!flag)
notEmpty.await();
System.out.println(Thread.currentThread().getName()+"^^^^消费者^^^^"+this.name);
flag=false;
notFull.signal();
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r=r;
}
public void run(){
while(true){
try {
r.set("+商品+");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r=r;
}
public void run(){
while(true){
try {
r.out();
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
}
class RCThread2{
public static void main(String[] args){
Resource r=new Resource();
Producer p =new Producer(r);
Consumer c =new Consumer(r);
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
new Thread(c).start();
}
}
|