JavaSE 多线程 线程间通讯—等待唤醒机制代码优化(背下来)

来源:互联网 发布:windows客户端开发 编辑:程序博客网 时间:2024/05/18 00:33
<span style="font-family:FangSong_GB2312;font-size:14px;">package ResourceDemo3;class Resource{private String name;private String sex;boolean flag=false;public synchronized  void set(String name,String sex){if (this.flag) try{this.wait();}catch(InterruptedException e){}//此处不规范,后续会解决这个问题this.name=name;this.sex=sex;this.flag=true;this.notify();}public synchronized void out(){if (!this.flag) try{this.wait();}catch(InterruptedException e){}//此处不规范,后续会解决这个问题System.out.println(name+"...+++.."+sex);this.flag=false;this.notify();}}//输入class Input implements Runnable{Resource r;Input(Resource r){this.r=r;}//Object obj=new Object();public void run(){int x=0;while (true) {if (x==0) {r.set("mike","nan");}else {r.set("丽丽","女女女女女女");}x=(x+1)%2;}}}//输出class Output implements Runnable{Resource r;//Object obj=new Object();Output(Resource r){this.r=r;}public void run(){while (true){r.out();}}}public class ResourceDemo3 {public static void main(String[] args) {//创建资源Resource r=new Resource();//创建任务Input in=new Input(r);Output out=new Output(r);//创建线程,执行路径Thread t1=new Thread(in);Thread t2=new Thread(out);//开启线程t1.start();t2.start();}}</span>

0 0