代码
生产者
public class PushTarget implements Runnable{
Tmall tmall;
public PushTarget(Tmall tmall){
this.tmall = tmall;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
tmall.push();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
消费者
public class TakeTarget implements Runnable{
Tmall tmall;
public TakeTarget(Tmall tmall){
this.tmall = tmall;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
tmall.take();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Tmall
public class Tmall {
int count;
public final int MAX_COUNT=10;
public synchronized void push(){
// 用while防止叫醒后执行count++
while (count >= MAX_COUNT) {
// 达到10,生产者停止生产,生产线程等待
System.out.println("达到10,生产者停止生产");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count++;
System.out.println("生产者,目前库存"+count);
// 生产完后通知等待的消费者线程
notifyAll();
}
public synchronized void take(){
while (count<=0) {
// 达到0,库存不够,消费线程等待
System.err.println("库存不够");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count--;
System.err.println("消费后剩余"+count);
// 消费后通知等待的生产线程
notifyAll();
}
}
测试
public class Main {
public static void main(String[] args) {
Tmall tmall = new Tmall();
TakeTarget t = new TakeTarget(tmall);
PushTarget p = new PushTarget(tmall);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
// new Thread(t).start();
}
}
网友评论