Java中多线程模拟包子铺造和 吃货吃包子
作者:互联网
包子铺:
import java.util.ArrayList; public class BaoZiPu implements Runnable { //定义变量:包子集合 ArrayList<String> baoZi; public BaoZiPu(ArrayList<String> baoZi) {//将包子集合作为构造方法的形参 this.baoZi = baoZi; } @Override public void run() { int number =0; while (true) {//模拟不停的造包子 synchronized (baoZi) {//同步代码块,所对象为包子集合 if (baoZi.size() > 0) {//有包子 try { baoZi.wait();//无限等待 } catch (InterruptedException e) { e.printStackTrace(); } } baoZi.add("包子" + number); System.out.println(Thread.currentThread().getName()+"包子铺造包子"+number); try { Thread.sleep(500);//模拟造包子时间 } catch (InterruptedException e) { e.printStackTrace(); } baoZi.notifyAll();//唤醒别的同一个所对象的线程 } number++; if (number == 20) { return;//做20个包子就下班 } } } }
吃货类:
import java.util.ArrayList; public class ChiHuo implements Runnable { //定义变量:包子集合 ArrayList<String> baoZi; public ChiHuo(ArrayList<String> baoZi) {//将包子集合作为构造方法的形参 this.baoZi = baoZi; } @Override public void run() { int number =0; while (true) {//模拟不停的吃包子 synchronized (baoZi) {//同步代码块,所对象为包子集合 if (baoZi.size() == 0) {//没有包子 try { baoZi.wait();//无限等待 } catch (InterruptedException e) { e.printStackTrace(); } } String str = baoZi.remove(0); System.out.println(Thread.currentThread().getName()+"吃货吃包子: "+str); try { Thread.sleep(500);//模拟吃包子时间 } catch (InterruptedException e) { e.printStackTrace(); } baoZi.notifyAll();//唤醒别的同一个所对象的线程 } number++; if (number == 20) { return;//吃20个包子就下班 } } } }
测试类:
import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test01 { public static void main(String[] args) { //在线程中模拟吃包子和包子铺做包子 //定义包子集合 ArrayList<String> baOZi = new ArrayList<>(); BaoZiPu bp = new BaoZiPu(baOZi);//创建包子铺对象 ChiHuo ch = new ChiHuo(baOZi);//创建吃货对象 ExecutorService pool = Executors.newFixedThreadPool(4);//创建有4个线程的线程池对象 pool.submit(bp);//让线程池执行包子铺线程 pool.submit(ch);//让线程池执行吃货线程 pool.submit(bp);//让线程池执行包子铺线程 pool.submit(ch);//让线程池执行吃货线程 } }
控制台打印效果:
标签:包子铺,ArrayList,吃货,number,public,baoZi,线程,多线程,包子 来源: https://blog.csdn.net/xilin6664/article/details/88926029