Java多线程常用方法 wait 和 notify
一:從一道面試題說起
啟動兩個線程, 一個輸出 1,3,5,7…99, 另一個輸出 2,4,6,8…100 最后 STDOUT 中按序輸出
1,2,3,4,5…100
要求用 Java 的 wait + notify 機制來實現
解法:
public class Test {private static Object lock = new Object();private static volatile int index = 0;public static void main(String[] args) {Runnable task = new Runnable() {public void run() {for(int i=0; i<50; i++) {synchronized (lock) {index++;System.out.println(index);try {if(index %2 ==0) {lock.notify();}else {lock.wait();}} catch (InterruptedException e) {e.printStackTrace();}}}}};new Thread(task).start();new Thread(task).start();} }二:wait and notify
首先看下wait方法的Java Doc介紹:
Causes the current thread to wait until either another thread invokes
the
* {@link java.lang.Object#notify()} method or the
* {@link java.lang.Object#notifyAll()} method for this object, or a
* specified amount of time has elapsed.
*
* The current thread must own this object’s monitor.
*
翻譯一下就是:
導致當前線程阻塞,一直等到別的線程調用了notify()或notifyAll()方法
當前線程必須持有這個 對象的鎖(monitor)
方法簽名:
public final native void wait(long timeout) throws InterruptedException;然后看下notify()的Java Doc介紹:
/**
* Wakes up a single thread that is waiting on this object’s
* monitor. If any threads are waiting on this object, one of them
* is chosen to be awakened. The choice is arbitrary and occurs at
* the discretion of the implementation.
翻譯一下大概就是:
喚醒任意一個正在等待當前對象的monitor鎖的線程。 若有多個線程處于此 object 控制權下的 wait 狀態,只有一個會被喚醒。
方法簽名:
public final native void notify();再看下notifyAll()的Java Doc介紹:
/**
* Wakes up all threads that are waiting on this object’s monitor. A
* thread waits on an object’s monitor by calling one of the
* {@code wait} methods.
翻譯一下大概就是:
喚醒所有正在等待當前對象的monitor鎖的線程。
方法簽名:
public final native void notifyAll();三:總結
wait 和 notify 均為 Object 的實例方法:
另外:
總結
以上是生活随笔為你收集整理的Java多线程常用方法 wait 和 notify的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网易举报雀巢向其提供腾讯二手制冰机,后者
- 下一篇: 锐捷推出 Wi-Fi 7 无线 AP 新