简单生产消费模式的代码流程(Java代码)
2016-12-11 16:00
459 查看
Student package july.star.thread12; /** * Student * @author MoXingJian * @email 939697374@qq.com * @date 2016年11月30日 下午3:39:45 * @version 1.0 */ public class Student { //定义成员变量 String name; Integer age; boolean flag; } GetThread package july.star.thread12; /** * GetThread * * @author MoXingJian * @email 939697374@qq.com * @date 2016年11月30日 下午3:42:05 * @version 1.0 */ public class GetThread implements Runnable { private Student s; public GetThread(Student s) { this.s = s; } @Override public void run() { while (true) { synchronized (s) { //1、没数据,flag默认为false,进来 if (!s.flag) { try { //2 :等待时释放锁 s.wait(); //10、回到这里继续执行 } catch (InterruptedException e) { e.printStackTrace(); } } //11、输出结果 System.out.println(s.name + ":" + s.age); //标记 s.flag = false; //12、标记并唤醒 //唤醒 s.notify(); //13、抢占执行权 } } } } SetThread package july.star.thread12; /** * SetThread * * @author MoXingJian * @email 939697374@qq.com * @date 2016年11月30日 下午3:40:31 * @version 1.0 */ public class SetThread implements Runnable { private Student s; private int count; public SetThread(Student s) { this.s = s; } @Override public void run() { while (true) { synchronized (s) { //3:没数据,为false,不走wait() if (s.flag) { try { s.wait(); //9、等待并释放锁,转到GetThread执行 } catch (InterruptedException e) { e.printStackTrace(); } } if (count % 2 == 0) { s.name = "一菲"; //4、赋值 s.age = 21; count++; } else { s.name = "二姐"; s.age = 28; count++; } //修改标记 s.flag = true; //6 //唤醒 s.notify(); //7、唤醒 } //8、 //抢占CPU执行权,SetThread有或GetThread有权执行 //假设SetThread又抢到了 } } } TestThread package july.star.thread12; /** * 简单生产消费模式 * @author MoXingJian * @email 939697374@qq.com * @date 2016年11月30日 下午3:43:19 * @version 1.0 */ public class TestThread { public static void main(String[] args) { //创建对象 Student s = new Student(); //创建线程 SetThread st = new SetThread(s); GetThread gt = new GetThread(s); Thread t1 = new Thread(st); Thread t2 = new Thread(gt); //开启线程 t1.start(); t2.start(); } }
相关文章推荐
- 一个简单的java生产着消费者模式的代码
- JAVA生产消费模式(代码及流程图)
- JAVA:将反射技术应用于工厂模式(Factory)和单例模式(Singleton)的简单代码
- JAVA代码之RocketMQ生产和消费数据
- 关于java多线程浅析一:简单实现生产消费模式
- 《黑马程序员》java笔记->生产消费多线程,同步代码块(优化代码)
- 线程的简单生产消费模式
- redis队列-生产消费模式-简单实现
- 模板设计模式,简单Java代码实现
- 对Java开发的思考(代码组织、设计模式、开发流程)
- 简单的java自动生产代码工具
- java多线程之生产消费模式
- 设计模式之四:简单工厂(披萨店生产披萨模拟流程)
- 大话设计模式1 简单工厂模式 的java代码实现
- 策略模式在java中的简单使用的代码
- 简单搭建kafka + zookeeper,附简单Java生产和消费客户端
- 适配器设计模式,简单的Java代码模拟
- JAVA代码之RocketMQ生产和消费数据
- 以Java代码为例讲解设计模式中的简单工厂模式
- 详解Java设计模式中的生产-消费者模式及代码实现