zoukankan      html  css  js  c++  java
  • JAVA线程锁lock下Condition的使用

    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * Lock下提供了一个condition条件,其中的condition提供了await和signal两个方法,
     * 起作用和Object提供的wait和notify相同,一个lock下可以有多个condition。
     * 
     * @author
     *
     *    例子,使用lock实现互斥,condition实现通信,来做子线程打印10次,主线程打印100次,如此反复
     */
    public class ConditionTest {
    
        public static void main(String[] args) {
            final Business business = new Business();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        business.sub();
                    }
                }
            }).start();
    
            while (true) {
                business.main();
            }
        }
    
        // ConditionTest.Business
        static class Business {
            private Lock lock = new ReentrantLock();
            private Condition cond = lock.newCondition();
            private boolean flag = true; // true : main run , false : sub run
    
            public void main() {
                lock.lock();
                try {
                    while (!flag) {
                        try {
                            cond.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for (int i = 1; i <= 100; i++) {
                        System.out.println("main of loop Number " + i);
                    }
                    flag = false;
                    cond.signal();
                } finally {
                    lock.unlock();
                }
            }
            public void sub() {
                lock.lock();
                try {
                    while (flag) {
                        try {
                            cond.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for (int i = 1; i <= 10; i++) {
                        System.out.println("sub of loop Number" + i);
                    }
                    flag = true;
                    cond.signal();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
  • 相关阅读:
    C#异常断电后重新启动项目出现配置未初始化错误
    TFS: 解决The build agent error
    删除TFS中的项目
    将现有项目添加到TFS中
    Typora开启行内公式
    Markdown上下标内容多于一项
    小甲鱼python基础教程飞机大战源码及素材
    Git 将本地库添加到远程仓库
    C# float与UInt16互转
    C++的重载流输出运算符
  • 原文地址:https://www.cnblogs.com/duwenlei/p/5112547.html
Copyright © 2011-2022 走看看