对于多线程之间的通讯的理解
2016-12-01 20:03
435 查看
老规矩,直接贴代码
package packageExercise; public class Demo1 { public static void main(String[] args) { Niuroumian product = new Niuroumian(); Mianguan producer = new Mianguan(product); Shike customer = new Shike(product); producer.start(); customer.start(); } } //牛肉面类 class Niuroumian{ String name;//名字 int price;//价格 int flag = 0; } //面馆类 class Mianguan extends Thread{ Niuroumian product;//牛肉面 int i = 0; public Mianguan(Niuroumian product) { this.product = product; } public void run() { while(true){ synchronized (product) { if(product.flag == 0){ if(i % 2 == 0){ product.name = "大碗牛肉面"; try { sleep(1);//此处让面馆线程睡1毫秒,增大线程出现安全问题的概率, } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } product.price = 10; }else{ product.name = "小碗牛肉面"; product.price = 5; } i++; System.out.println("面馆拉好了" + product.name + product.price); product.flag = 1; product.notify(); }else{ try { product.wait(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } } } } //食客类 class Shike extends Thread{ Niuroumian product; public Shike(Niuroumian product) { this.product = product; } public void run() { while(true){ synchronized (product) { if (product.flag == 1) { System.out.println("食客吃完了" + product.name + product.price); product.flag = 0; product.notify(); } else{ product.notify(); } } } } }
相关文章推荐
- 对于JAVA多线程中线程之间的通信方式的理解
- [多线程] ManualResetEvent(线程之间通讯 通知或者查看是否完成)
- 线程开发之多线程之间的通讯实现
- 对于多线程的理解
- 【Java多线程】多线程之间实现通讯与生产者与消费者模式
- 多线程之间实现通讯,join,yield,lock
- VC++ 多线程之间的通讯
- (三)多线程之间实现通讯
- 对于java多线程的理解(一)
- java多线程中对于join方法的理解
- 简单的多线程之间的通讯
- java 中多线程之间的通讯之生产者和消费者 (多个线程之间的通讯)
- java 中多线程之间的通讯之等待唤醒机制
- Java 多线程学习笔记 线程通讯 wait notify notifyAll的理解
- iOS 视图在不同View之间的切换(对于convertRect:函数的一些理解)
- 对于多线程编程的互斥锁和条件变量以及信号量的理解
- 对于多线程概念的理解
- qt 多线程之间通讯
- 如何快速掌握plc或工控机与其他设备的modbus通讯协议?包括格式与实际过程 RT,本人从事工控行业多年,对于PLC与触摸屏也算比较熟悉,唯独对这个通讯协议比较难理解,请教高人指导,从什么地方开始下手,或者是说如何正确理解报文格式或正确写入
- 多线程之间通讯(synchronized,wait,notify)