Java通過wait()和notifyAll()方法實現(xiàn)線程間通信
本文實例為大家分享了Java實現(xiàn)線程間通信的具體代碼,供大家參考,具體內(nèi)容如下
Java代碼(使用了2個內(nèi)部類):
package Threads;
import java.util.LinkedList;
/**
* Created by Frank
*/
public class ProdCons {
protected LinkedList<Object> list = new LinkedList<>();
protected int max;
protected boolean done = false;
public static void main(String[] args) throws InterruptedException {
ProdCons prodCons = new ProdCons(100, 3, 4);
Thread.sleep(5 * 1000);
synchronized (prodCons.list) {
prodCons.done = true;
try {
prodCons.notifyAll();
} catch (Exception ex) {
}
}
}
private ProdCons(int maxThreads, int nP, int nC) {
this.max = maxThreads;
for (int i = 0; i < nP; i++) {
new Producer().start();
}
for (int i = 0; i < nC; i++) {
new Consumer().start();
}
}
class Producer extends Thread {
public void run() {
while (true) {
Object justProduced = null;
try {
justProduced = getObj();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (list) {
while (list.size() == max) {
try {
list.wait();
} catch (InterruptedException e) {
System.out.println("Producer INTERRUPTED");
}
}
list.addFirst(justProduced);
list.notifyAll();
System.out.println("Produced 1;List size now " + list.size());
if (done) {
break;
}
}
}
}
}
class Consumer extends Thread {
public void run() {
while (true) {
Object object = null;
synchronized (list) {
if (list.size() == 0) {
try {
list.wait();
} catch (InterruptedException e) {
System.out.println("Consumer INTERRUPTED");
}
}
if (list.size() > 0) {
object = list.removeLast();
}
list.notifyAll();
System.out.println("List size now " + list.size());
if (done) {
break;
}
}
if (null != object) {
System.out.println("Consuming object " + object);
}
}
}
}
private Object getObj() throws InterruptedException {
Thread.sleep(1000);
return new Object();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis 中的一對一,一對多,多對多的配置原則示例代碼
這篇文章主要介紹了 Mybatis 中的一對一,一對多,多對多的配置原則示例代碼,需要的朋友可以參考下2017-03-03
springboot + rabbitmq 如何實現(xiàn)消息確認(rèn)機制(踩坑經(jīng)驗)
這篇文章主要介紹了springboot + rabbitmq 如何實現(xiàn)消息確認(rèn)機制,本文給大家分享小編實際開發(fā)中的一點踩坑經(jīng)驗,內(nèi)容簡單易懂,需要的朋友可以參考下2020-07-07
maven tomcat plugin實現(xiàn)熱部署
這篇文章主要介紹了maven tomcat plugin實現(xiàn)熱部署,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
基于maven搭建一個ssm的web項目的詳細(xì)圖文教程
這篇文章主要介紹了基于maven搭建一個ssm的web項目的詳細(xì)教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
Spring使用Redis限制用戶登錄失敗的次數(shù)及暫時鎖定用戶登錄權(quán)限功能
這篇文章主要介紹了Spring使用Redis限制用戶登錄失敗的次數(shù)及暫時鎖定用戶登錄權(quán)限功能,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02
Java 普通代碼塊靜態(tài)代碼塊執(zhí)行順序(實例講解)
下面小編就為大家?guī)硪黄狫ava 普通代碼塊靜態(tài)代碼塊執(zhí)行順序(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
struts2+jsp+jquery+Jcrop實現(xiàn)圖片裁剪并上傳實例
本篇文章主要介紹了struts2+jsp+jquery+Jcrop實現(xiàn)圖片裁剪并上傳實例,具有一定的參考價值,有興趣的可以了解一下。2017-01-01

