Condition,Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
- public class ThreadTest {
- public static void main(String[] args) {
- final Business business = new Business();
- new Thread(new Runnable() {
- @Override
- public void run() {
- threadExecute(business, "sub");
- }
- }).start();
- threadExecute(business, "main");
- }
- public static void threadExecute(Business business, String threadType) {
- for(int i = 0; i < 100; i++) {
- try {
- if("main".equals(threadType)) {
- business.main(i);
- } else {
- business.sub(i);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- class Business {
- private boolean bool = true;
- private Lock lock = new ReentrantLock();
- private Condition condition = lock.newCondition();
- public /*synchronized*/ void main(int loop) throws InterruptedException {
- lock.lock();
- try {
- while(bool) {
- condition.await();//this.wait();
- }
- for(int i = 0; i < 100; i++) {
- System.out.println("main thread seq of " + i + ", loop of " + loop);
- }
- bool = true;
- condition.signal();//this.notify();
- } finally {
- lock.unlock();
- }
- }
- public /*synchronized*/ void sub(int loop) throws InterruptedException {
- lock.lock();
- try {
- while(!bool) {
- condition.await();//this.wait();
- }
- for(int i = 0; i < 10; i++) {
- System.out.println("sub thread seq of " + i + ", loop of " + loop);
- }
- bool = false;
- condition.signal();//this.notify();
- } finally {
- lock.unlock();
- }
- }
- }
复制代码
Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法。
|
|