最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

線程的生產(chǎn)者和消費(fèi)者管程法的代碼

2020-04-15 10:27 作者:小垃圾kiki  | 我要投稿
package cn.jd.cooperation;

/*
?* 使用管程法實(shí)現(xiàn)生產(chǎn)者消費(fèi)者模式
?*/
public class CoTest01 {
?? ?public static void main(String[] args) {
?? ??? ?SynContainer container=new SynContainer();
?? ??? ?new Productor(container).start();
?? ??? ?new Consumer(container).start();
?? ?}
}

//多線程的生產(chǎn)者
class Productor extends Thread {
?? ?SynContainer container;

?? ?public Productor(SynContainer container) {
?? ??? ?this.container = container;
?? ?}

?? ?@Override
?? ?public void run() {
?? ??? ?// 生產(chǎn)
?? ??? ?for (int i = 1; i < 100; i++) {
?? ??? ??? ?System.out.println("生產(chǎn)第 -->"+i+"個饅頭");
?? ??? ??? ?container.push(new Steamedbun(i)); //new了饅頭的對象
?? ??? ?}
?? ?}
}

//多線程的消費(fèi)者
class Consumer extends Thread {
?? ?SynContainer container;

?? ?public Consumer(SynContainer container) {
?? ??? ?this.container = container;
?? ?}

?? ?@Override
?? ?public void run() {
?? ??? ?// 消費(fèi)
?? ??? ?for (int i = 0; i < 1000; i++) {
?? ??? ??? ?System.out.println("消費(fèi)第-->"+container.pop().id+"個饅頭");
?? ??? ??? ?
?? ??? ?}
?? ?}
}

//緩沖區(qū)
class SynContainer {
?? ?// 存儲數(shù)據(jù)的容器
?? ?Steamedbun[] buns = new Steamedbun[10];
?? ?int count = 0;// 計數(shù)器
?? ?// 儲存-->生產(chǎn)者做的事情

?? ?public synchronized void push(Steamedbun bun) {
?? ??? ?//何時能生產(chǎn)? 容器存在空間
?? ??? ?//不能生產(chǎn)? 只有等待
?? ??? ?if(count==buns.length) {
?? ??? ??? ?try {
?? ??? ??? ??? ?this.wait();??? //線程阻塞,消費(fèi)者通知生產(chǎn)解除
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//存在空間可以生產(chǎn)
?? ??? ?buns[count] = bun;
?? ??? ?count++;
?? ??? ?//存在數(shù)據(jù)了,可以通知消費(fèi)了
?? ??? ?this.notifyAll();
?? ?}

?? ?// 獲取-->消費(fèi)者做的事情
?? ?public synchronized Steamedbun pop() {
?? ??? ?//何時消費(fèi)??? 看容器中是否存在數(shù)據(jù)
?? ??? ?//沒有數(shù)據(jù)只有等待
?? ??? ?if(count==0) {
?? ??? ??? ?try {
?? ??? ??? ??? ?this.wait();//線程阻塞?? 生產(chǎn)者通知消費(fèi)解除阻塞
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//存在數(shù)據(jù)可以消費(fèi)
?? ??? ?count--;
?? ??? ?Steamedbun bun = buns[count];
?? ??? ?this.notifyAll();//消費(fèi)了有空間了就可以通知你生產(chǎn)了
?? ??? ?return bun;
?? ?}

}

//饅頭
class Steamedbun {
?? ??? ?int id;

?? ??? ?public Steamedbun(int id) {
?? ??? ??? ?this.id = id;
?? ??? ?}
?? ??? ?
}

線程的生產(chǎn)者和消費(fèi)者管程法的代碼的評論 (共 條)

分享到微博請遵守國家法律
中山市| 托克逊县| 孝感市| 河北省| 丹江口市| 筠连县| 唐海县| 钦州市| 兴业县| 故城县| 广丰县| 利辛县| 神池县| 海城市| 广昌县| 莲花县| 浮山县| 马鞍山市| 贵州省| 临城县| 疏附县| 芦溪县| 西宁市| 湘潭市| 瑞金市| 华坪县| 资中县| 镇远县| 兖州市| 株洲县| 贵定县| 织金县| 原平市| 无棣县| 老河口市| 吴川市| 泽普县| 乐山市| 沙田区| 会理县| 阳谷县|