• threadCondition 线程问题(老大打印一次,让老二打印二次,再老三打印三次,再老大打印一次....以此类推)


    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class ThreadConditionTest {

    public static void main(String[] args) {

    final Print print = new Print();
    // 老大
    new Thread(new Runnable() {
    @Override
    public void run() {
    while(true){
    print.sub_1();
    }
    }
    }).start();
    // 老二
    new Thread(new Runnable() {
    @Override
    public void run() {
    while(true){
    print.sub_2();
    }
    }
    }).start();
    // 老三
    new Thread(new Runnable() {
    @Override
    public void run() {
    while(true){
    print.sub_3();
    }
    }
    }).start();
    }

    }

    class Print {
    //控制谁该打印
    int who = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();


    void sub_1() {
    lock.lock();

    while(who != 1){
    try {
    condition1.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    for (int i = 0; i < 1; i++) {
    System.out.println("sub_1" + " " + "1");
    }
    //改成老二该打标识
    who = 2;
    //叫醒老二
    condition2.signal();//如果先解锁,lock.unlock();再叫醒老二,会抛出异常,因为signal()方法只能在同步代码中被调用
    lock.unlock();
    }

    void sub_2() {
    lock.lock();

    while(who != 2){
    try {
    condition2.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    for (int i = 0; i < 2; i++) {
    System.out.println("sub_2" + " " + "1");
    }

    who = 3;
    condition3.signal();
    lock.unlock();
    }

    void sub_3() {
    lock.lock();
    while(who != 3){
    try {
    condition3.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    for (int i = 0; i < 3; i++) {
    System.out.println("sub_3" + " " + "1");
    }
    who =1;
    condition1.signal();
    lock.unlock();
    }
    }

    想的都是好
  • 相关阅读:
    清北学堂2019.7.18 & 清北学堂2019.7.19
    清北学堂2019.7.17
    清北学堂2019.7.16
    清北学堂2019.7.15
    清北学堂2019.7.14
    清北学堂2019.7.13
    【洛谷P1383 高级打字机】
    考试整理
    考试整理
    【洛谷P5018 对称二叉树】
  • 原文地址:https://www.cnblogs.com/freezone/p/4951547.html
Copyright © 2020-2023  润新知