zoukankan      html  css  js  c++  java
  • 线程按序交替

    /*
     * Copyright (c) XXX Corp.
     * All Rights Reserved.
     */
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * Main.
     *
     * @author Feng Yongkang, 2020/10/26
     * @version XXX v1.0
     */
    public class Main {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            AlternateDemo alternateDemo = new AlternateDemo();
            new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    alternateDemo.loop1();
                }
            }, "线程A").start();
            new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    alternateDemo.loop2();
                }
            }, "线程B").start();
            new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    alternateDemo.loop3();
                }
            }, "线程C").start();
        }
    }
    
    class AlternateDemo {
      //交替的信号
    private int number = 1; private Lock lock = new ReentrantLock();
      //多线程下控制方法跟随信号执行
    private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); public void loop1() { lock.lock(); try { if (number != 1) { condition1.await(); } System.out.println(Thread.currentThread().getName()); number = 2; condition2.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void loop2() { lock.lock(); try { if (number != 2) { condition2.await(); } System.out.println(Thread.currentThread().getName()); number = 3; condition3.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void loop3() { lock.lock(); try { if (number != 3) { condition3.await(); } System.out.println(Thread.currentThread().getName()); number = 1; condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
  • 相关阅读:
    《Java面向对象编程》
    大学计算机基础考试系统(CS)
    企业物资管理系统
    IP.21出现的错误
    假如你的年龄超过了23···
    如何经营婚姻
    一张舞女图测试你的左右脑切换能力【我看到左右都转呢~】
    无法加载DLL(oci.dll)
    mongodb安装信息及有关命令
    loaded the "controller" nib but the view outlet was not set.问题解决
  • 原文地址:https://www.cnblogs.com/xiaoeyu/p/13880597.html
Copyright © 2011-2022 走看看