【重点】等待唤醒机制
来源:互联网 发布:java图片上传下载 编辑:程序博客网 时间:2024/04/28 10:50
等待唤醒机制极大地提高了cpu资源的利用,节约了时间
package com.xiaozhi.mythread;/* * 等待唤醒机制 * 等待和唤醒方法必须在锁内,因为是锁调用这两个方法 * 因为锁不固定,所以wait和notify是Object方法 */public class Test {public static void main(String[] args) {Res res=new Res();Input input=new Input(res);Output output=new Output(res);Thread thread1=new Thread(input);Thread thread2=new Thread(output);thread1.start();thread2.start();}}class Res{String name;String sex;boolean flag;}class Input implements Runnable{private Res res;private boolean flag=true;public Input(Res res) {super();this.res = res;}@Overridepublic void run() {while(true){synchronized (res) {if(res.flag){try {res.wait();} catch (InterruptedException e) {e.printStackTrace();}}//输入if(flag){res.name="mike";res.sex="man";flag=false;}else{res.name="丽丽";res.sex="女女女";flag=true;}res.flag=true;res.notify();}}}}class Output implements Runnable{private Res res;public Output(Res res) {super();this.res = res;}@Overridepublic void run() {while(true){synchronized (res) {if(!res.flag){try {res.wait();} catch (InterruptedException e) {e.printStackTrace();}}//输出System.out.println(res.name+"---------------"+res.sex);res.flag=false;res.notify();}}}}
代码优化很重要
package com.xiaozhi.threadinformation;/*代码优化 */public class Test2 {public static void main(String[] args) {Res res=new Res();Input input=new Input(res);Output output=new Output(res);Thread thread1=new Thread(input);Thread thread2=new Thread(output);thread1.start();thread2.start();}}class Res{private String name;private String sex;private boolean resFlag=false;public synchronized void input(String name,String sex){if(resFlag){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}this.name=name;this.sex=sex;this.resFlag=true;this.notify();}public synchronized void output(){if(!this.resFlag){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}//输出System.out.println(this.name+"---------------"+this.sex);this.resFlag=false;this.notify();}}class Input implements Runnable{private Res res;private boolean perFlag=true;public Input(Res res) {super();this.res = res;}@Overridepublic void run() {while(true){if(perFlag){res.input("mike","man");perFlag=false;}else{res.input("丽丽","女女女");perFlag=true;}}}}class Output implements Runnable{private Res res;public Output(Res res) {super();this.res = res;}@Overridepublic void run() {while(true)res.output();}}
- 【重点】等待唤醒机制
- java等待唤醒机制
- 多线程等待唤醒机制
- 等待唤醒机制
- 等待唤醒机制
- Java 等待/唤醒机制
- 线程等待唤醒机制
- 等待唤醒机制
- 多线程-等待唤醒机制
- 等待唤醒机制
- 等待唤醒机制
- 多线程之等待唤醒机制
- 多线程的等待唤醒机制
- 黑马程序员--等待唤醒机制
- 线程的等待唤醒机制
- java多线程等待唤醒机制
- 多线程通讯-等待唤醒机制
- 等待唤醒机制_小记
- 图片合成
- 动态hash思想方法
- 图片处理小结
- 移动周报:七大无需编程的DIY开发工具
- java自学笔记之static
- 【重点】等待唤醒机制
- Android SDK文档Resources下的Articles——总结
- java多线程
- Cocaine是Yandex推出的开源PaaS服务
- Godaddy域名转出步聚 (转)
- 解决 android版wikipedia 无法使用问题
- ubuntu12.04启用root用户登录
- 【wikioi】1004 四子连棋
- UVA 10759 Dice Throwing