之前的代码没有考虑容器里为空的现象,当生产一个商品时,可能cpu会在消费者里一直运行,从而消费多个空产品。wait是一个异常,使用时要进行捕获。notify是苏醒线程。
class Resourse {
private Object[] os = new Object[1];
private Object obj = new Object();
public void put(Object o) {
synchronized (obj) {
if (os[0] != null) {//给一个判断,如果容器里还有商品那么就让线程等一下
try {
obj.wait();
} catch (InterruptedException e) {
}
}
os[0] = o;
System.out.println(Thread.currentThread().getName() + "生产出来的---" + os[0]);
obj.notify();//既然有等待那么就要有苏醒。
}
}
public void get() {
synchronized (obj) {
if (os [0]== null) {//给一个判断,如果容器里没有商品那么就让线程等一下
try {
obj.wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + "消耗的---" + os[0]);
os[0] = null;
obj.notify();
}
}
}
class Sheng implements Runnable {
private Resourse r;
Sheng(Resourse r) {
this.r = r;
}
public void run() {
int num = 0;
while (true) {
r.put("自行车" + num);
num++;
}
}
}
class Xiao implements Runnable {
private Resourse r;
Xiao(Resourse r) {
this.r = r;
}
public void run() {
while (true) {
int num = 0;
r.get();
num++;
}
}
}
class Demo1 {
public static void main(String[] args) {
Resourse r = new Resourse();
Sheng s = new Sheng(r);
Xiao x = new Xiao(r);
Thread ss = new Thread(s);
Thread ss2 = new Thread(x);
ss.start();
ss2.start();
}
}