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();
    }
    }
    });
    }
    }
    }

  • 相关阅读:
    poj 3159 Candies
    强连通分量——Tarjan算法
    nyoj 次方求模
    nyoj 快速查找素数
    nyoj 光棍节的快乐
    拓扑排序
    快速幂取模
    nyoj 最大素因子
    素数打表
    nyoj 数的长度
  • 原文地址:https://www.cnblogs.com/chinaifae/p/10188891.html
Copyright © 2011-2022 走看看