线程协作-生产者/消费者模式

上一篇讲述了线程的互斥(同步),但是在很多情况下,仅仅同步是不够的,还需要线程与线程协作(通信),生产者/消费者模式是一个经典的线程同步以及通信的模型。

        假设有这样一种情况,有一个盘子,盘子里只能放一个鸡蛋,A线程专门往盘子里放鸡蛋,如果盘子里有鸡蛋,则一直等到盘子里没鸡蛋,B线程专门从盘子里取鸡蛋,如果盘子里没鸡蛋,则一直等到盘子里有鸡蛋。这里盘子是一个互斥区,每次放鸡蛋是互斥的,每次取鸡蛋也是互斥的,A线程放鸡蛋,如果这时B线程要取鸡蛋,由于A没有释放锁,B线程处于等待状态,进入阻塞队列,放鸡蛋之后,要通知B线程取鸡蛋,B线程进入就绪队列,反过来,B线程取鸡蛋,如果A线程要放鸡蛋,由于B线程没有释放锁,A线程处于等待状态,进入阻塞队列,取鸡蛋之后,要通知A线程放鸡蛋,A线程进入就绪队列。我们希望当盘子里有鸡蛋时,A线程阻塞,B线程就绪,盘子里没鸡蛋时,A线程就绪,B线程阻塞,代码如下:

  1. import java.util.ArrayList; 
  2. import java.util.List; 
  3. /** 定义一个盘子类,可以放鸡蛋和取鸡蛋 */ 
  4. public class Plate { 
  5.     /** 装鸡蛋的盘子 */ 
  6.     List<Object> eggs = new ArrayList<Object>(); 
  7.     /** 取鸡蛋 */ 
  8.     public synchronized Object getEgg() { 
  9.         while (eggs.size() == 0) { 
  10.             try
  11.                 wait(); 
  12.             } catch (InterruptedException e) { 
  13.                 e.printStackTrace(); 
  14.             } 
  15.         } 
  16.         Object egg = eggs.get(0); 
  17.         eggs.clear();// 清空盘子 
  18.         notify();// 唤醒阻塞队列的某线程到就绪队列 
  19.         System.out.println("拿到鸡蛋"); 
  20.         return egg; 
  21.     } 
  22.     /** 放鸡蛋 */ 
  23.     public synchronized void putEgg(Object egg) { 
  24.         while (eggs.size() > 0) { 
  25.             try
  26.                 wait(); 
  27.             } catch (InterruptedException e) { 
  28.                 e.printStackTrace(); 
  29.             } 
  30.         } 
  31.         eggs.add(egg);// 往盘子里放鸡蛋 
  32.         notify();// 唤醒阻塞队列的某线程到就绪队列 
  33.         System.out.println("放入鸡蛋"); 
  34.     } 
  35.     static class AddThread extends Thread { 
  36.         private Plate plate; 
  37.         private Object egg = new Object(); 
  38.         public AddThread(Plate plate) { 
  39.             this.plate = plate; 
  40.         } 
  41.         public void run() { 
  42.             plate.putEgg(egg); 
  43.         } 
  44.     } 
  45.     static class GetThread extends Thread { 
  46.         private Plate plate; 
  47.         public GetThread(Plate plate) { 
  48.             this.plate = plate; 
  49.         } 
  50.         public void run() { 
  51.             plate.getEgg(); 
  52.         } 
  53.     } 
  54.     public static void main(String args[]) { 
  55.         Plate plate = new Plate(); 
  56.         for(int i = 0; i < 10; i++) { 
  57.             new Thread(new AddThread(plate)).start(); 
  58.             new Thread(new GetThread(plate)).start(); 
  59.         } 
  60.     } 
import java.util.ArrayList;
import java.util.List;
/** 定义一个盘子类,可以放鸡蛋和取鸡蛋 */
public class Plate {
	/** 装鸡蛋的盘子 */
	List<Object> eggs = new ArrayList<Object>();
	/** 取鸡蛋 */
	public synchronized Object getEgg() {
		while (eggs.size() == 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Object egg = eggs.get(0);
		eggs.clear();// 清空盘子
		notify();// 唤醒阻塞队列的某线程到就绪队列
		System.out.println("拿到鸡蛋");
		return egg;
	}
	/** 放鸡蛋 */
	public synchronized void putEgg(Object egg) {
		while (eggs.size() > 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		eggs.add(egg);// 往盘子里放鸡蛋
		notify();// 唤醒阻塞队列的某线程到就绪队列
		System.out.println("放入鸡蛋");
	}
	static class AddThread extends Thread {
		private Plate plate;
		private Object egg = new Object();
		public AddThread(Plate plate) {
			this.plate = plate;
		}
		public void run() {
			plate.putEgg(egg);
		}
	}
	static class GetThread extends Thread {
		private Plate plate;
		public GetThread(Plate plate) {
			this.plate = plate;
		}
		public void run() {
			plate.getEgg();
		}
	}
	public static void main(String args[]) {
		Plate plate = new Plate();
		for(int i = 0; i < 10; i++) {
			new Thread(new AddThread(plate)).start();
			new Thread(new GetThread(plate)).start();
		}
	}
}
        输出结果:

  1. 放入鸡蛋 
  2. 拿到鸡蛋 
  3. 放入鸡蛋 
  4. 拿到鸡蛋 
  5. 放入鸡蛋 
  6. 拿到鸡蛋 
  7. 放入鸡蛋 
  8. 拿到鸡蛋 
  9. 放入鸡蛋 
  10. 拿到鸡蛋 
  11. 放入鸡蛋 
  12. 拿到鸡蛋 
  13. 放入鸡蛋 
  14. 拿到鸡蛋 
  15. 放入鸡蛋 
  16. 拿到鸡蛋 
  17. 放入鸡蛋 
  18. 拿到鸡蛋 
  19. 放入鸡蛋 
  20. 拿到鸡蛋 
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
        8 l程序开始,A线程判断盘子是否为空,放入一个鸡蛋,并且唤醒在阻塞队列的一个线程,阻塞队列为空;假设CPU又调度了一个A线程,盘子非空,执行等待,这个A线程进入阻塞队列;然后一个B线程执行,盘子非空,取走鸡蛋,并唤醒阻塞队列的A线程,A线程进入就绪队列,此时就绪队列就一个A线程,马上执行,放入鸡蛋;如果再来A线程重复第一步,在来B线程重复第二步,整个过程就是生产者(A线程)生产鸡蛋,消费者(B线程)消费鸡蛋。

        前段时间看了张孝祥老师线程的视频,讲述了一个其学员的面试题,也是线程通信的,在此也分享一下。

        题目:子线程循环10次,主线程循环100次,如此循环100次,好像是空中网的笔试题。

  1. public class ThreadTest2 { 
  2.     public static void main(String[] args) { 
  3.         final Business business = new Business(); 
  4.         new Thread(new Runnable() { 
  5.             @Override 
  6.             public void run() { 
  7.                 threadExecute(business, "sub"); 
  8.             } 
  9.         }).start(); 
  10.         threadExecute(business, "main"); 
  11.     }    
  12.     public static void threadExecute(Business business, String threadType) { 
  13.         for(int i = 0; i < 100; i++) { 
  14.             try
  15.                 if("main".equals(threadType)) { 
  16.                     business.main(i); 
  17.                 } else
  18.                     business.sub(i); 
  19.                 } 
  20.             } catch (InterruptedException e) { 
  21.                 e.printStackTrace(); 
  22.             } 
  23.         } 
  24.     } 
  25. class Business { 
  26.     private boolean bool = true
  27.     public synchronized void main(int loop) throws InterruptedException { 
  28.         while(bool) { 
  29.             this.wait(); 
  30.         } 
  31.         for(int i = 0; i < 100; i++) { 
  32.             System.out.println("main thread seq of " + i + ", loop of " + loop); 
  33.         } 
  34.         bool = true
  35.         this.notify(); 
  36.     }    
  37.     public synchronized void sub(int loop) throws InterruptedException { 
  38.         while(!bool) { 
  39.             this.wait(); 
  40.         } 
  41.         for(int i = 0; i < 10; i++) { 
  42.             System.out.println("sub thread seq of " + i + ", loop of " + loop); 
  43.         } 
  44.         bool = false
  45.         this.notify(); 
  46.     } 
public class ThreadTest2 {
	public static void main(String[] args) {
		final Business business = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				threadExecute(business, "sub");
			}
		}).start();
		threadExecute(business, "main");
	}	
	public static void threadExecute(Business business, String threadType) {
		for(int i = 0; i < 100; i++) {
			try {
				if("main".equals(threadType)) {
					business.main(i);
				} else {
					business.sub(i);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
class Business {
	private boolean bool = true;
	public synchronized void main(int loop) throws InterruptedException {
		while(bool) {
			this.wait();
		}
		for(int i = 0; i < 100; i++) {
			System.out.println("main thread seq of " + i + ", loop of " + loop);
		}
		bool = true;
		this.notify();
	}	
	public synchronized void sub(int loop) throws InterruptedException {
		while(!bool) {
			this.wait();
		}
		for(int i = 0; i < 10; i++) {
			System.out.println("sub thread seq of " + i + ", loop of " + loop);
		}
		bool = false;
		this.notify();
	}
}

        大家注意到没有,在调用wait方法时,都是用while判断条件的,而不是if,在wait方法说明中,也推荐使用while,因为在某些特定的情况下,线程有可能被假唤醒,使用while会循环检测更稳妥
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园整体解决方案是响应国家教育信息化政策,结合教育改革和技术创新的产物。该方案以物联网、大数据、人工智能和移动互联技术为基础,旨在打造一个安全、高效、互动且环保的教育环境。方案强调从数字化校园向智慧校园的转变,通过自动数据采集、智能分析和按需服务,实现校园业务的智能化管理。 方案的总体设计原则包括应用至上、分层设计和互联互通,确保系统能够满足不同用户角色的需求,并实现数据和资源的整合与共享。框架设计涵盖了校园安全、管理、教学、环境等多个方面,构建了一个全面的校园应用生态系统。这包括智慧安全系统、校园身份识别、智能排课及选课系统、智慧学习系统、精品录播教室方案等,以支持个性化学习和教学评估。 建设内容突出了智慧安全和智慧管理的重要性。智慧安全管理通过分布式录播系统和紧急预案一键启动功能,增强校园安全预警和事件响应能力。智慧管理系统则利用物联网技术,实现人员和设备的智能管理,提高校园运营效率。 智慧教学部分,方案提供了智慧学习系统和精品录播教室方案,支持专业级学习硬件和智能化网络管理,促进个性化学习和教学资源的高效利用。同时,教学质量评估中心和资源应用平台的建设,旨在提升教学评估的科学性和教育资源的共享性。 智慧环境建设则侧重于基于物联网的设备管理,通过智慧教室管理系统实现教室环境的智能控制和能效管理,打造绿色、节能的校园环境。电子班牌和校园信息发布系统的建设,将作为智慧校园的核心和入口,提供教务、一卡通、图书馆等系统的集成信息。 总体而言,智慧校园整体解决方案通过集成先进技术,不仅提升了校园的信息化水平,而且优化了教学和管理流程,为学生、教师和家长提供了更加便捷、个性化的教育体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值