JAVA基础之等待/唤醒机制

来源:互联网 发布:电子显微镜原理 知乎 编辑:程序博客网 时间:2024/04/29 01:22
涉及的方法:
1.wait();让线程处于冻结状态,被wait的线程会被存储到线程池中。
2.notify();唤醒线程池中的任意一个线程。
3.notifyAll();唤醒线程池中的所有线程。


注意:这些方法都必须定义在同步中。
因为这些方法都是用于操作线程状态的方法,
必须要明确到底操作的是哪个锁上的线程。


为什么操作线程的wait notify notifyAll方法都定义在Object类中?
因为这些方法是监视器的方法,监视器就是锁。

锁可以是任意的对象,任意对象调用的方式一定定义在Object类中。

//资源class Resource{String name;String sex;boolean flag=false;}//输入class Input implements Runnable{Resource r;Input(Resource r){this.r=r;}public void run(){int x=0;while (true){synchronized(r){if (r.flag){try{r.wait();}catch(InterruptedException e){}}if (x==0){r.name="mike";r.sex="nan";}else {r.name="凌晗";r.sex="女女女女女";}r.flag=true;r.notify(); }x=(x+1)%2;}}}//输出class Output implements Runnable{Resource r;Output(Resource r){this.r=r;}public void run(){while (true){synchronized(r){if (!r.flag){try{r.wait();}catch(InterruptedException e){}}System.out.println(r.name+".........."+r.sex);r.flag=false;r.notify();}}}}/*代码优化*/class Resource1{private String name;private String sex;private boolean flag=false;public synchronized void set(String name,String sex){if (flag){try{this.wait();}catch(InterruptedException e){}}this.name=name;this.sex=sex;flag=true;this.notify();}public synchronized void out(){if (!flag){try{this.wait();}catch(InterruptedException e){}}System.out.println(name+".........."+sex);flag=false;this.notify();}}//输入class Input1 implements Runnable{Resource1 r;Input1(Resource1 r){this.r=r;}public void run(){int x=0;while (true){if (x==0){r.set("mike","nan");}else {r.set("凌晗","女女女女女");}x=(x+1)%2;}}}//输出class Output1 implements Runnable{Resource1 r;Output1(Resource1 r){this.r=r;}public void run(){while (true){r.out();}}}class ResourceDemo2 {public static void main(String[] args) {//创建资源/*Resource r=new Resource();//创建任务Input in=new Input(r);Output on=new Output(r);//创建线程Thread t1=new Thread(in);Thread t2=new Thread(on);//开启线程t1.start();t2.start();*/Resource1 r=new Resource1();//创建任务Input1 in=new Input1(r);Output1 on=new Output1(r);//创建线程Thread t1=new Thread(in);Thread t2=new Thread(on);//开启线程t1.start();t2.start();}}


0 0
原创粉丝点击