Java-Thread-生产者消费模式
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
}
}
}