多线程同步锁实现简单数据的同步输入与输出
2017-04-30 23:21
323 查看
多线程同步锁实现简单数据的同步输入与输出
Resource类class Resource { public String name; public int age; boolean flag = false; }
Input类
/** * Created by Aongi on 2017/4/30. * Version 1.0 */ class Input implements Runnable { private final Resource r; public Input(Resource r) { this.r = r; } @Override public void run() { int a = 0; //noinspection InfiniteLoopStatement while (true) { synchronized (r) { if (r.flag) { try { r.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (a % 2 == 0) { r.name = "张三"; r.age = 20; } else { r.name = "李四"; r.age = 22; } r.flag = true; r.notify(); } a++; } } }
Output类
/** * Created by Aongi on 2017/4/30. * Version 1.0 */ class Output implements Runnable { private final Resource r; public Output(Resource r) { this.r = r; } @Override public void run() { //noinspection InfiniteLoopStatement while (true) { synchronized (r) { if (!r.flag) { try { r.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(r.name + "——————" + r.age); r.flag = false; r.notify(); } } } }
最后来个Test类
/** * Created by Aongi on 2017/4/30. * Version 1.0 */ class Test { //main方法 public static void main(String[] args) { Resource r = new Resource(); Input input = new Input(r); Output output = new Output(r); Thread in = new Thread(input); Thread out = new Thread(output); in.start(); out.start(); } }
相关文章推荐
- 2,改写本章例2.1程序,要求: (1)将数据成员改为私有; (2)将输入和输出的功能改为由成员函数实现; (3)在类体内定义成员函数;
- 网络游戏中,玩家数据同步的一种简单实现
- 编写一个void sort(int*x,int n)实现将x数组中的n个数据从大到小排序。n及数组元素在主函数中输入。将结果显示在屏幕上并输出到文件
- rsync数据镜像备份+inotify实时同步的简单实现
- C语言用数组1. 简单约瑟夫环问题: N个人,编号从1~N围成一圈,输入一个数T,从1号开始报数,报到T的人出圈;下一人又从1开始报数,下一个报到T的人出圈,输出出圈顺序。 考虑问实现约瑟夫环问题
- C语言实现数据输入与输出的函数
- 将ip地址转成二进制数据,除基本输入输出不调用库函数实现
- ACM入门------C语言中如何实现多组数据输入输出
- python中json格式数据输出的简单实现方法
- 使用Jsp实现数据的输入与输出
- 使用汇编实现从标准输入获取数据和标准输出输出数据
- 用触发器实现数据简单同步
- 如何利用s3c2440的gpio实现数据输入和输出
- Hadoop(十):简单了解Hadoop数据类型,输入输出格式及用户如何自定义。
- 用switch 语句实现简单的计算器功能(要求从键盘输入操作数和运算符)。 例如:输入: 3 * 4 输出:12
- 很棒的!从标准输入文件流读取多行数据并且存放到文件---两种实现;标准输入流到文件再到标准输出流
- loner_li 机试题 编写一个简单的计算器实现加减乘除:输入两个数字和一个运算符号,输出结果(注意容错性)
- 简单的C++程序 c++语言的输入和输出(基本数据类型)
- 用java编写一个简单的字符串加密解密程序,将字符串分成若干行,实现字符串以一列一列读取,并还原之前输入的字符串。这里实现4行输出。
- goLang实现一个控制台的输入和输出(最简单的那种)