【重点】等待唤醒机制

来源:互联网 发布: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();}}


原创粉丝点击