日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java多线程常用方法 wait 和 notify

發布時間:2023/12/4 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 的實例方法:

  • Object.wait()——暫停一個線程
  • Object.notify()——喚醒一個線程
  • Object.notifyAll()——喚醒所有等待Object對象鎖的線程
  • 另外:

  • 都需要擁有Object對象鎖才能調用
  • 可以使用此機制進行多線程之間的協同、通信,實現多線程的可見性
  • 總結

    以上是生活随笔為你收集整理的Java多线程常用方法 wait 和 notify的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。