线程间通讯-------等待唤醒机制
2015-11-14 17:27
337 查看
/* 线程间通讯: 其实就是多个线程在操作同一个资源, 但是操作的动作不同 */ class Res2 { String name; String sex; boolean flag=false; } class Input2 implements Runnable { private Res2 r; Input2(Res2 r) { this.r=r; } public void run() { int x=0; while(true) { /* 要找一个共同的不变的对象,如果在Output2和Input2中都建立Object obj=new Object(); 两者用的对象是不同的,还是解决不了之前的问题。 */ synchronized(r) { if(r.flag) try { r.wait(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if(x==0) { r.name="mike"; r.sex="man"; } else { r.name="丽丽"; r.sex="女女女女女女女"; } x=(x+1)%2; r.flag=true; r.notify(); } } } } class Output2 implements Runnable { private Res2 r; Output2(Res2 r) { this.r=r; } public void run() { while(true) { synchronized(r) { if(!r.flag) try { r.wait(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } System.out.println(r.name+"......"+r.sex); r.flag=false; r.notify(); } } } } public class tongxun2 { public static void main(String[] args) { Res2 r=new Res2(); Input2 in=new Input2(r); Output2 out =new Output2(r); Thread t1=new Thread(in); Thread t2=new Thread(out); t1.start(); t2.start(); } } /* wait; notify(); notifyAll; 都使用在同步中,因为要对持有监视器(锁)的线程操作。 所以要使用在同步中,因为只有同步才有所。 为什么这些操作线程的方法要定义在Object类中? 因为这些方法在操作同步线程时,都必须要标示它们锁操作线程只有的锁。 只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒。 不可以对不同锁中的线程进行唤醒。 也就是说,等待和唤醒必须是同一个锁。 而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。 */
结果:
进去一个,输出一个。。。。。。。。。。。。
相关文章推荐
- Myeclipse设置注释模板
- java读取文件夹所有文件
- Android 之异步加载LoaderManager
- 例题4-5 UVa512 Spreadsheet Tracking
- BizTalk 2010 学习笔记
- WingIde的快捷键
- 怎样快速的遍历json的属性 然后将属性添入数组
- kendo ui的treeView节点点击事件修改和grid的配置的一点总结
- React-Native尝鲜计划-环境搭建及 hello world
- C++源文件名与函数名
- 适合智商180以上的两人对弈游戏
- c# dynamic动态类型和匿名类
- 个人博客作业WEEK7
- 删除Repository中的文件
- HA集群配置
- Uva 12166 严格平衡树
- 九度OJ 1283:第一个只出现一次的字符 (计数)
- MongoDB小结01 - MongoDB简介
- 九度OJ 1283:第一个只出现一次的字符 (计数)
- 测试准备工作《全程软件测试》