package com.heima.code;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
InputOutputThreadDemo06是InputOutputThreadDemo05的一个升级版
利用的知识是Lock
JDK1.5中提供了多线程升级解决方案。
将同步Synchronized替换成了现实Lock操作。
将Object中的wait(),notify(),nottifyAll(),替换成了
Condition对象中的,await(),single(),singleAll().
该对象可以Lock锁,进行获取。
*/
class ResourceDemo06{
private String name;
private int count;
public boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();
try{
while(flag)
condition_pro.await();//s生产者等待
this.name = name+"......"+count++;
System.out.println(Thread.currentThread().getName()+"++++++"+this.name);
flag = true;
condition_con.signal();//消费者唤醒
}
finally{
lock.unlock();
}
}
public void out() throws InterruptedException{
lock.lock();
try{
while(!flag)
condition_con.await();//消费者等待
System.out.println(Thread.currentThread().getName()+"------"+this.name);
flag = false;
condition_pro.signal();//生产者唤醒
}
finally{
lock.unlock();
}
}
}
class ProducerDemo06 implements Runnable{
private ResourceDemo06 resd06;
ProducerDemo06(ResourceDemo06 resd06){
this.resd06 = resd06;
}
@Override
public void run() {
while(true){
try {
resd06.set("商品");
} catch (InterruptedException e) {
}
}
}
}
class ConsumerDemo06 implements Runnable{
private ResourceDemo06 resd06;
ConsumerDemo06(ResourceDemo06 resd06){
this.resd06 = resd06;
}
@Override
public void run() {
while(true){
try {
resd06.out();
} catch (InterruptedException e) {
}
}
}
}
public class InputOutputThreadDemo06 {
public static void main(String[] args) {
ResourceDemo06 resd06 = new ResourceDemo06();
ProducerDemo06 pro = new ProducerDemo06(resd06);
ConsumerDemo06 con = new ConsumerDemo06(resd06);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|
|