zoukankan      html  css  js  c++  java
  • ReentrantLock、Condition结合使用实现多线程通讯

    package maptoxml;

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;

    public class SemaphoreTest {
    static volatile private ReentrantLock lock = new ReentrantLock();
    static volatile private Condition condition = lock.newCondition();
    static volatile private Boolean isWait = false;

    private static void test() throws InterruptedException {
    lock.lock();// 只有一个线程可以执行下面的代码
    if (!isWait) {
    System.out.println(Thread.currentThread().getName() + "进入了等待");
    isWait = true;
    condition.await();
    System.out.println(Thread.currentThread().getName() + "被唤醒");
    } else {
    isWait = false;
    condition.signalAll();
    System.out.println(Thread.currentThread().getName() + "唤醒了所有的线程");
    }
    lock.unlock();
    }

    public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 2; i++) {// 开启两个线程
    executorService.execute(new Runnable() {
    @Override
    public void run() {
    try {
    test();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    }
    }
    }

  • 相关阅读:
    ubuntu下安装maven
    159.Longest Substring with At Most Two Distinct Characters
    156.Binary Tree Upside Down
    155.Min Stack
    154.Find Minimum in Rotated Sorted Array II
    153.Find Minimum in Rotated Sorted Array
    152.Maximum Product Subarray
    151.Reverse Words in a String
    150.Evaluate Reverse Polish Notation
    149.Max Points on a Line
  • 原文地址:https://www.cnblogs.com/chinaifae/p/10188891.html
Copyright © 2011-2022 走看看