多线程的等待唤醒机制
2014-04-13 22:41
621 查看
一把锁一把钥匙。。就是等待跟唤醒要在同一锁内
/* 多线程的等待唤醒机制 wait(); noyify(); */ class Pes { String name; String sex; boolean flag = false; } class Inp implements Runnable { private Pes p; Inp(Pes p) { this.p = p; } public void run() { int x=0; while(true) { synchronized(p){ if(p.flag) try{p.wait();}catch(Exception e){} if(x==0){ p.name ="nike"; p.sex = "man"; } else { p.name = "mike"; p.sex = "women"; } x= (x+1)%2; p.flag= true; p.notify(); } } } } class Out implements Runnable { private Pes p; Out(Pes p) { this.p = p; } public void run() { while(true) { synchronized(p) { if(!p.flag) try{p.wait();}catch(Exception e){} System.out.println(p.name+"..."+p.sex); p.flag = false; p.notify(); } } } } class Test_12_3 { public static void main(String[] args) { System.out.println("Hello Wolrd"); Pes p = new Pes(); Inp i = new Inp(p); Out o = new Out(p); Thread t1 = new Thread(i); Thread t2 = new Thread(o); t1.start(); t2.start(); } } //notifyAll(); /* wait: notify(); notifyAll(); 都使用在同步中。因为要对持有监视器(锁)的线程操作。 所以要使用在同步中,因为只有同步才具有锁。 为什么这些操作线程的方法要定义Object类中呢? 因为这些方法在操作同步中线程时,都必须要标识它们所操作线程只有的锁。 只有用一个锁上的被等待线程。可以被同一个锁上notify唤醒。 不可以对不同锁中的线程进行唤醒。 也就是说。等待和唤醒必须是同一个锁 */
相关文章推荐
- 深入探讨 Java 类加载器
- java文件操作类实例
- 黑马程序员_OC中的分类(Category)的使用
- 安装opencms时遇到问题及解决方法
- CAsyncSocket编程 MFC
- 关于人生的思考
- jvm
- ubuntu12.04中如何设定中文输入法
- Leetcode | Merge Intervals
- JQuery页面回车事件
- 湖南科技大学2014 ACM 校赛
- 3Sum Closest
- tomcat类加载器
- 组合索引leaf 数据存储
- PB实现数据窗口的多表更新
- SecureCRT 上传和下载文件
- C和C++中return的用法
- MEF核心笔记(6)让 MEF 拥抱 AOP
- 组合索引leaf 数据存储
- sgu 题目分类