package com.lianxi.thread;
/**
* 模拟一个人生产50个玩具,每200毫秒生产一个,当生产到第20个时加入每秒吃1个馒头,共吃完3个后在接着生产的多线程。
*/
public class Person2 {
int toy=0;
int steamedbun=1;
public synchronized void ManufactureToys(){//使用 synchronized 保证线程安全
while (toy<50){//当其他线程调用 notify 通知时,继续生产玩具,直到生产达到50个为止。
toy++;
System.out.println(Thread.currentThread().getName()+"生产的第"+toy+"个玩具");
if (toy==20){//当玩具数量达到20时,线程会进入等待状态,同时释放锁,允许其他线程执行
System.out.println("生产到第"+toy+"个玩具,开始吃馒头");
try {
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
notify();
}
}
public synchronized void EatsteamedBun(){
while (steamedbun<=3){
System.out.println(Thread.currentThread().getName()+"吃第"+steamedbun+"个馒头");
if(steamedbun==3){
try {
wait();//在吃到第3个馒头时,线程会进入等待状态,释放锁,等待其他线程的通知。
}catch (InterruptedException e){
e.printStackTrace();
}
break;
}else {
steamedbun++;
}
notify();
}
}
}
class Produc extends Thread{
private Person2 person2;
public Produc(Person2 person2){
this.person2=person2;
}
@Override
public void run() {
try {
sleep(200);
}catch (InterruptedException e){
e.printStackTrace();
}
person2.ManufactureToys();
}
}
class Eat extends Thread{//吃馒头的分线程
private Person2 person2;
public Eat(Person2 person2){
this.person2=person2;
}
@Override
public void run() {
try{
sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
person2.EatsteamedBun();
}
}
class PersonTest{//分别启动两个线程。这样,生产者和消费者可以并发执行,模拟了玩具的生产和馒头的消费过程。
public static void main(String[] args){
Person2 p=new Person2();
Produc p1=new Produc(p);
Eat e=new Eat(p);
p1.setName("一号生产人员");
e.setName("一号生产人员");
e.start();
p1.start();
}
}
模拟一个人生产50个玩具,每200毫秒生产一个,当生产到第20个时加入每秒吃1个馒头,共吃完3个后在接着生产的多线程。
最新推荐文章于 2024-05-11 23:45:19 发布