溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java多線程wait()和notify()如何使用

發(fā)布時(shí)間:2021-11-30 17:16:39 來(lái)源:億速云 閱讀:116 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下java多線程wait()和notify()如何使用,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

注:wait()和notify()應(yīng)當(dāng)用在synchronized內(nèi)
package com.test;
import java.util.ArrayList;
public class ThreadWaitTeste {
public static void main(String[] args) {
ArrayList<String> ar = new ArrayList<String>();
Product p = new Product(ar);
Consumer c = new Consumer(ar);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Product implements Runnable{
ArrayList<String>  array;
public Product(ArrayList<String> array){
this.array= array;
}
public void run() {
while (true){
     synchronized(array){
if(this.array.size()<5){
this.array.add("test!");
this.array.add("test!");
this.array.add("test!");
this.array.add("test!");
System.out.println("Product size : "+array.size());
}else{
System.out.println("Product wait size : "+array.size()+"數(shù)量少于5,等待......");
try {
array.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class Consumer implements Runnable{
ArrayList<String>  array;
public Consumer(ArrayList<String> array){
this.array= array;
}
public void run() {
while(true){
synchronized(array){
if(this.array.size()>=5){
this.array.remove(1);
System.out.println("Consumer size : "+array.size());
}else{
try {
array.notifyAll();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}

看完了這篇文章,相信你對(duì)“java多線程wait()和notify()如何使用”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI