在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    java中條件等待

    雖然可以使用object的wait、notify,也仍然是很多人的選擇;但是不便于把一組相關(guān)聯(lián)的條件封裝在一起。

    用Lock和Condition則可以實(shí)現(xiàn).

    示例代碼

    Lock relaLock = new ReentrantLock();

    Condition relaCondition1 = relaLock.newCondition();

    Condition relaCondition2 = relaLock.newCondition();

    Thread thread1 = new Thread(() -> {

    long i = 0;

    while (i++ < Long.MAX_VALUE) {

    if (i % 100000000 != 0) {

    continue;

    }

    System.out.println(“thread1 i:” + (i / 100000000));

    if (i / 100000000 < 10) {//not wait condition

    continue;

    }

    try {

    relaLock.lock();

    relaCondition1.await();

    i=0;

    } catch (InterruptedException ex) {

    System.out.println(“thread flag:” + Thread.currentThread().isInterrupted());

    } finally {

    relaLock.unlock();

    }

    }

    });

    thread1.start();

    Thread.sleep(10000L);

    try {

    relaLock.lock();

    System.out.println(“relaCondition1 signal”);

    relaCondition1.signalAll();

    }finally {

    relaLock.unlock();

    }

    thread1.join();

    輸出

    thread1 i:1

    thread1 i:2

    thread1 i:3

    thread1 i:4

    thread1 i:5

    thread1 i:6

    thread1 i:7

    thread1 i:8

    thread1 i:9

    thread1 i:10

    relaCondition1 signal

    thread1 i:1

    thread1 i:2

    thread1 i:3

    thread1 i:4

    鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權(quán)歸原作者所有,如有侵權(quán)請聯(lián)系管理員(admin#wlmqw.com)刪除。
    用戶投稿
    上一篇 2022年6月30日 20:05
    下一篇 2022年6月30日 20:05

    相關(guān)推薦

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時間:周一至周五,10:30-18:30,節(jié)假日休息