五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(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)者管程法的代碼的評論 (共 條)

分享到微博請遵守國家法律
海盐县| 临泽县| 四会市| 东光县| 亳州市| 信丰县| 宁河县| 荃湾区| 铁力市| 石棉县| 东乌| 门源| 文登市| 合作市| 吴堡县| 莫力| 庆安县| 龙里县| 盐山县| 微博| 洛宁县| 多伦县| 遵化市| 湖州市| 开平市| 台前县| 汾阳市| 丽江市| 江口县| 克什克腾旗| 陆河县| 衡水市| 梁平县| 会泽县| 象州县| 双城市| 晋宁县| 东城区| 闸北区| 兴海县| 洞头县|