同步线程的一种经典设计模式。
public class Test {
public static void main(String[] args) {
Quene q = new Quene();
Producter producter = new Producter(q);
Customer customer = new Customer(q);
producter.start();
customer.start();
}
}
//生产者
public class Producter extends Thread {
private Quene quene;
public Producter(Quene quene) {
this.quene = quene;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
quene.setItem(i);
System.out.println("生产者:生产产品" + i);
}
}
}
//消费者
public class Customer extends Thread {
private Quene quene;
public Customer(Quene quene) {
this.quene = quene;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("消费者:获得产品" + quene.getItem());
}
}
}
//销售列队
public class Quene {
private int item;
private boolean isFull = false;
public synchronized int getItem() {
if (!isFull) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isFull = false;
this.notify();
return item;
}
//因为使用notify()所有要加上 synchronized
//synchronized 对方法修饰的时候等同与
// synchronized(this){ ...... }
public synchronized void setItem(int item) {
if (!isFull) {
this.item = item;
isFull = true;
this.notify();
}
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}