以前写的生产者消费者线程问题
package com.synchronze;
public class Store {
private final int MAX_SIZE;
private int count;
public Store(int n) {
MAX_SIZE = n;
count = 0;
}
public synchronized void add() {
while (count >= MAX_SIZE) {
System.out.println("已经满了");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println(Thread.currentThread().toString() + "put" + count);
this.notifyAll();
}
public synchronized void remove() {
while (count <= 0) {
System.out.println("已经空了");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().toString() + "get" + count);
count--;
this.notifyAll();
}
public static void main(String[] args) {
Store s = new Store(5);
Thread pro = new Producer(s);
Thread con = new Consumer(s);
Thread pro2 = new Producer(s);
Thread con2 = new Consumer(s);
pro.setName("producer");
con.setName("consumer");
pro.setName("producer2");
con.setName("consumer2");
pro.start();
pro2.start();
con.start();
con2.start();
}
}
class Producer extends Thread {
private Store s;
public Producer(Store s) {
this.s = s;
}
public void run() {
while (true) {
s.add();
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread {
private Store s;
public Consumer(Store s) {
this.s = s;
}
public void run() {
while (true) {
s.remove();
try {
Thread.sleep(1200);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在所有的Java根类java.langObject中,包含了三个重载的wait()方法以及notify()和natifyall()方法。他们主要的作用在于让当前的线程进入等待池或从等待池中唤醒一个或多个线程继续执行。正是通过他们,才能很好的解决生产者消费者模型的问题。以上实例,由于生产者线程执行更快,因此程序会间歇性的打印类似以下结果:
Thread[producer2,5,main]put1
Thread[Thread-2,5,main]put2
Thread[consumer2,5,main]get2
Thread[Thread-3,5,main]get1
Thread[producer2,5,main]put1
Thread[Thread-2,5,main]put2
Thread[Thread-3,5,main]get2
Thread[consumer2,5,main]get1
Thread[Thread-2,5,main]put1
Thread[producer2,5,main]put2
Thread[consumer2,5,main]get2
Thread[Thread-3,5,main]get1
Thread[Thread-2,5,main]put1
Thread[producer2,5,main]put2
Thread[producer2,5,main]put3
Thread[Thread-2,5,main]put4
Thread[consumer2,5,main]get4
Thread[Thread-3,5,main]get3
Thread[Thread-2,5,main]put3
Thread[producer2,5,main]put4
Thread[Thread-3,5,main]get4
Thread[consumer2,5,main]get3
Thread[Thread-2,5,main]put3
Thread[producer2,5,main]put4
Thread[producer2,5,main]put5
已经满了
Thread[Thread-3,5,main]get5
Thread[Thread-2,5,main]put5
Thread[consumer2,5,main]get5
Thread[producer2,5,main]put5
已经满了
Thread[Thread-3,5,main]get5
Thread[Thread-2,5,main]put5
Thread[consumer2,5,main]get5
Thread[producer2,5,main]put5
已经满了
已经满了
…………………………
同理,如果消费者线程执行更快,则会打印多个“已经空了”