import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test_Producer_Consumer {
public static void main(String[] args) {
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/*
* class Resource { private String name; private int count = 1; private boolean
* flag = false;
*
* public synchronized void set(String name) { while(flag) { try { this.wait();
* } catch (InterruptedException e) { e.printStackTrace(); } } this.name = name
* + "..." + count++; System.out.println(Thread.currentThread().getName() +
* "...生产了..." + name); flag = true; this.notifyAll(); }
*
* public synchronized void out() { while(!flag) { try { this.wait(); } catch
* (InterruptedException e) { e.printStackTrace(); } }
* System.out.println(Thread.currentThread().getName() + "...消费了.............."
* + name); flag = false; this.notifyAll(); } }
*/
class Resource {
private String name;
private int count = 1;
private boolean flag = false;
/*
* JDK5.0对线程同步问题进行了升级
*/
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name) {
lock.lock();
try {
while (flag) {
condition_pro.await();
}
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName() + "...生产了..."
+ name);
flag = true;
condition_con.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally { // 不管你await有没有出错,你的锁一定会要释放
lock.unlock();
}
}
public void out() {
lock.lock();
try {
while (!flag) {
condition_con.await();
}
System.out.println(Thread.currentThread().getName()
+ "...消费了.............." + name);
flag = false;
condition_pro.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally { // 不管你await有没有出错,你的锁一定会要释放
lock.unlock();
}
}
}
class Producer implements Runnable {
private Resource res;
Producer(Resource res) {
this.res = res;
}
@Override
public void run() {
while (true) {
res.set("商品");
}
}
}
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
@Override
public void run() {
while (true) {
res.out();
}
}
}
JDK5.0对多线程同步进行了升级
将隐式的synchronized替换成了显式的Lock对象
将Object对象中的wait、notify、notifyAll,替换成了Condition对象
因为等待和唤醒是针对锁对象的,所以Condition对象的实例可以通过Lock对象的newCondition()方法拿到
并且升级之后最大的好处是一个锁对象可以对应多个Condition对象,这样在生产者消费者的例子中就可以解决
唤醒的时候把本方唤醒的问题,通过不同的Condition对象,可以选择让哪些Condition对象等待,哪些Condition对象唤醒