public class PushTarget implements Runnable{
private Tmail tmail;
public PushTarget(Tmail tmail) {
this.tmail = tmail;
}
@Override
public void run() {
while(true) {
tmail.push();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TakeTarget implements Runnable{
private Tmail tmail;
public TakeTarget(Tmail tmail) {
this.tmail = tmail;
}
@Override
public void run() {
while(true) {
tmail.take();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Tmail {
private int count;
public final int MAX_COUNT=10;
public synchronized void push() {
while(count>=MAX_COUNT) {
try {
System.out.println(Thread.currentThread().getName()+"库存达到上线,生产者停止生产。。。。。");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println(Thread.currentThread().getName()+"生产者生产,当前库存为:"+count);
notifyAll();
}
public synchronized void take() {
while(count<=0) {
try {
System.out.println(Thread.currentThread().getName()+"当前库存为:"+count+",消费者等待。");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
System.out.println(Thread.currentThread().getName()+"消费者消费。");
notifyAll();
}
public static void main(String[] args) {
Tmail tmail = new Tmail();
PushTarget t = new PushTarget(tmail);
TakeTarget t2 = new TakeTarget(tmail);
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
}
}