/* * JDK1.5中提供了多线程升级解决方案 * 将同步Synchronized替换成Lock操作。 * * 将Object中的wait,notify,notifyAll,都可以用Condition对象替换 * 该对象可以用 Lock锁,进行获取。 * * 该示例中,实现了本方只唤醒对方操作 * */ package test.itheima; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class GeneraterConsumerDemo { /** * @param args */ public static void main(String[] args) { System.out.println("Start"); ResourceNew r = new ResourceNew(); GeneratorNew g = new GeneratorNew(r); ConsumerNew c = new ConsumerNew(r); Thread t1 = new Thread(g); Thread t2 = new Thread(c); Thread t3 = new Thread(g); Thread t4 = new Thread(c); t1.start(); t2.start(); t3.start(); t4.start(); } } class ResourceNew { private String name; private int count = 1; private boolean flag = false; private Lock lock = new ReentrantLock(); private Condition condition_con = lock.newCondition(); private Condition condition_gen = lock.newCondition(); public void set(String name) { lock.lock(); try { while (flag) { condition_gen.await(); } this.name = name + "--" + count++; System.out.println(Thread.currentThread().getName() + "---生产者" + this.name); flag = true; condition_con.signal(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { lock.unlock(); } } public void out(String name) { lock.lock(); try { while (!flag) { condition_con.await(); } System.out.println(Thread.currentThread().getName() + "------消费者" + this.name); flag = false; condition_gen.signal(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { lock.unlock(); } } } class GeneratorNew implements Runnable { private ResourceNew res; GeneratorNew(ResourceNew res) { this.res = res; } public void run() { while (true) { res.set("+商品 +"); } } } class ConsumerNew implements Runnable { private ResourceNew res; ConsumerNew(ResourceNew res) { this.res = res; } public void run() { while (true) { res.out("+消费 +"); } } }
[黑马程序员]多线程_JDK1.5新特性,Lock的使用
最新推荐文章于 2014-04-19 22:48:51 发布