JDK1.5中将Lock接口代替synchronized升级为显示的锁机制,
将Object中的wait、notify、notifyAll替换成了Condition对象中的await、signal、signalAll该对象可以通过Lock进行获取
该示例中实现了本方线程只唤醒对方线程的操作
import java.util.concurrent.locks.*; /* JDK1.5 中提供了多线程升级解决方案。 将同步Synchronized替换成显示Lock操作。 将Object中的wait,notify notifyAll,替换了Condition对象。 该对象可以Lock锁 进行获取。 该示例中,实现了本方只唤醒对方操作。 Lock:替代了Synchronized lock unlock newCondition() Condition:替代了Object wait notify notifyAll await(); signal(); signalAll(); */ //资源类 class Resource { private String name; private int count = 1; private boolean flag = false; //设置锁对象(通过Lock接口的实现类ReentrantLock) private Lock lock = new ReentrantLock(); //设置Condition对象,用于对线程进行可控的休眠唤醒操作(await、signal、signalAll) Condition condition_pro = lock.newCondition();//对生产者操作 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.signal(); } catch (Exception e) { } finally { lock.unlock();//将释放锁的动作放到finally中使其一定会被执行。 } } //消费资源 public void get() { try { lock.lock(); while (!flag) { condition_con.await(); } System.out.println(Thread.currentThread().getName()+".........."+name); flag = false; condition_pro.signal(); } catch (Exception e) { } finally { lock.unlock(); } } } //生产者类 class producer implements Runnable { private Resource r; producer(Resource r) { this.r = r; } public void run() { while (true) { r.set("+商品+"); } } } //消费者类 class consumer implements Runnable { private Resource r; consumer(Resource r) { this.r = r; } public void run() { while (true) { r.get(); } } } class LockDemo { public static void main(String[] args) { //资源类 Resource r = new Resource(); //实现了Runnable接口的生产者类、消费者类 producer pro = new producer(r); consumer con = new consumer(r); //生产者线程 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(); // Thread t11 = new Thread(pro); // Thread t22 = new Thread(pro); // Thread t33 = new Thread(con); // Thread t44 = new Thread(con); // t11.start(); // t22.start(); // t33.start(); // t44.start(); } }