1. 程式人生 > >Java-Thread-生產者消費模式

Java-Thread-生產者消費模式

ide 沒有 john lean pos con clas catch this

package com.cn.thread;

import java.util.ArrayList;
import java.util.List;
/**
* 模擬 生產者消費模式
* @author johnzhang
*
*/
public class WaitAndNotifyMain {
public static void main(String[] args) {
WaitAndNotify waitAndNotify = new WaitAndNotify();
Runnable r1 = new Thread1(waitAndNotify);
Runnable r2 = new Thread2(waitAndNotify);
new Thread(r2).start();
new Thread(r1).start();

}
}

class Thread1 implements Runnable {
WaitAndNotify waitAndNotify;

public Thread1(WaitAndNotify waitAndNotify) {
this.waitAndNotify = waitAndNotify;
}

@Override
public void run() {
// TODO Auto-generated method stub
waitAndNotify.getList();
}

}

class Thread2 implements Runnable {
WaitAndNotify waitAndNotify;

public Thread2(WaitAndNotify waitAndNotify) {
this.waitAndNotify = waitAndNotify;
}

@Override
public void run() {
// TODO Auto-generated method stub
waitAndNotify.setList();
}

}

class WaitAndNotify {
private int size;
private List<String> context;
private boolean isok = false;

public WaitAndNotify() {
this.size = 10;
context = new ArrayList<String>();
// for (int i = 0; i < size; i++) {
// context.add("值" + (i + 1));
// }
}

public synchronized void setList() {
try {
while (true) {
if(isok){
System.out.println(" 做 好啦獲取" + isok);
this.wait();
}else{
for (int i = 1; i <= size; i++) {
System.out.println("要制作啦啦,制作的東西是:食物" + i );
context.add("食物" + i);
Thread.sleep(500);
}
isok = true;
this.notify();
}

}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}

public synchronized void getList() {
try {
while (true) {
if(!isok){
System.out.println("沒有 食物 禁止用戶 吃" + isok);
this.wait();
}else{
System.out.println("有 食物 用戶 吃" + isok);
for (int i = 1; i <= size; i++) {
System.out.println("要消費啦,消費的東西是" + context.get(0) + " I = " + i +" Context.size = " + context.size());
System.out.println("Context.value" + context.toString());
context.remove(0);//每次吃掉第一個
Thread.sleep(500);
// System.out.println("睡眠後返回 i=============== " + i);
}
isok = false;
this.notify();
}
}

} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}

Java-Thread-生產者消費模式