Lock接口
package com.google; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Demo { private int i = 100; Lock lock = new ReentrantLock(); //synchronized public void seal() { lock.lock(); try { while (i > 0) { i = i - 1; System.out.println(Thread.currentThread().getName() + "\t" + i); } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } public class LockDemo { public static void main(String[] args) { Demo demo = new Demo(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 50; i++) { demo.seal(); } } }, "AA").start(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 50; i++) { demo.seal(); } } }, "BB").start(); } }
曹肖扬
19913146193