生产者、消费者多线程例题
public class test2 {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producter producter = new Producter(clerk);
producter.setName("生产者");
Consumer consumer = new Consumer(clerk);
consumer.setName("消费者");
producter.start();
consumer.start();
}
}
class Clerk //店员类,作为消费者和生产者的共享资源,共享资源要考虑线程安全问题
{
private int count = 0;
public synchronized void produce(){
if(count < 20){
count++;
System.out.println("生产者正在生产第"+count+"件商品");
notify(); //释放消费wait
}
else
{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void consume(){ //当一个线程进入生产,其他线程无法进入消费,同步监视器是this,指向相同。
if(count > 0){
System.out.println("消费者正在消费第"+count+"件商品");
count--;
notify(); //释放生产wait
}
else
{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producter extends Thread{
private Clerk clerk;
public Producter(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
int num = 0;
System.out.println(getName()+"开始生产商品");
while (true) {
num++;
clerk.produce();
if(num == 100){ //生产100次停止操作
break;
}
}
}
}
class Consumer extends Thread{
private Clerk clerk;
public Consumer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
int num = 0;
System.out.println(getName()+"开始消费商品");
while (true) {
num++;
clerk.consume();
if(num == 100){ //消费100次停止操作
break;
}
}
}
}