package cn.itcast.day27_Prictice;
import java.util.ArrayList;
/**
* 生产一个,消费一个;
* 等待唤醒机制(单生产者单消费者)
* 选作(能看懂最后的包子案例即可)
*/
public class Prictice2 {
public static void main(String[] args) throws InterruptedException {
// 创建一个集合容器
ArrayList<String> list = new ArrayList<>();
In in = new In(list);
Out out = new Out(list);
// 创建线程对象
Thread thread1 = new Thread(in,"商家");
Thread thread2 = new Thread(out,"买家");
// 间接启动线程
thread1.start();
Thread.sleep(2000);
thread2.start();
while(true) {
Thread.sleep(1000);
System.out.println("------------------------包子总数:"+list.size()+"个");
}
}
}
In类:
package cn.itcast.day27_Prictice;
import java.util.ArrayList;
public class In implements Runnable {
// 声明一个私有属性
private ArrayList<String> list;
private int count;
In(ArrayList<String> list) {
this.list = list;
}
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 同步
synchronized (list) {
// 处理,如果数量大于200 ,就让线程等待
if (list.size() > 200) {
try {
list.wait(); // 等待被唤醒,会顺序执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "-做包子" + count+"个");
list.add("包子" + count++);
list.notify();
}
}
}
}
Out类:
package cn.itcast.day27_Prictice;
import java.util.ArrayList;
public class Out implements Runnable {
private int count;
private ArrayList<String> list;
Out(ArrayList<String> list) {
this.list = list;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 同步!
synchronized (list) {
if (list.size() < 20) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String remove = list.remove(0);
System.out.println(Thread.currentThread().getName() + "-买" + remove+"个");
if (list.size() > 20) {
// 唤醒
list.notify();
}
}
}
}
}
|
|