今天早上敲代碼時發現了好多問題,Xiao(RongQi r) {this.r = r;},這段代碼我一直搞不懂,既然上面已經private RongQi r,為什么還要多此一舉,其實創建Xiao對象時把RongQi 對象地址傳給this.r也就是private RongQi r的r這樣你調用put,get方法時就能找到RongQi對象。
多生產多消費要注意一個問題,等待喚醒機制是在判斷里面的,當一個生產者喚醒另外一個生產者時,沒有進行判斷就進行生產了,那么就會造成安全問題,所以將if語句換成while語句,喚醒語句要改成notifyAll,因為會出現生產與消費都在線程池里的現象。
class RongQi {
private Object[] o = new Object[1];
private Object obj = new Object();
int num = 0;
public void put(Object obj) {
synchronized (obj) {
while (o[0] != null) {
try {
obj.wait();
} catch (InterruptedException e) {
}
o[0] = obj+"--"+num;
num++;
System.out.println(Thread.currentThread().getName() + "生產者生產的---" +o[0]);
obj.notifyAll();
}
}
}
public void get() {
synchronized (obj) {
while (o[0] == null) {
try {
obj.wait();
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + "消費者消費的---" +o[0]);
o[0]=null;
obj.notifyAll();
}
}
}
}
class Chan implements Runnable {
private RongQi r;
Chan(RongQi r) {
this.r = r;
}
public void run() {
while (true) {
r.put("牛奶");
}
}
}
class Xiao implements Runnable {
private RongQi r;
Xiao(RongQi r) {
this.r = r;
}
public void run() {
while (true) {
r.get();
}
}
}
class Demo1 {
public static void main(String[] args) {
RongQi r = new RongQi();
Chan c = new Chan(r);
Xiao x = new Xiao(r);
Chan c1 = new Chan(r);
Xiao x1 = new Xiao(r);
Thread t = new Thread(c);
Thread t2 = new Thread(c1);
Thread t3 = new Thread(x);
Thread t4 = new Thread(x1);
t.start();
t2.start();
t3.start();
t4.start();
}
}