Java 并发 线程间通信 等待/通知的经典范式

来源:互联网 发布:json字符串格式化输出 编辑:程序博客网 时间:2024/05/29 03:18

实例代码:

import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.TimeUnit;public class WaitNotify {    static boolean flag=true;    static Object lock=new Object();    public static void main(String[] args) throws Exception{        Thread waitThread=new Thread(new Wait(),"WaitThread");        waitThread.start();        TimeUnit.SECONDS.sleep(1);        Thread notifyThread=new Thread(new Notify(),"notifyThread");        notifyThread.start();    }    static class Wait implements Runnable{        @Override        public void run() {            synchronized(lock){                //当条件不满足时候,等待wait,释放锁                while(flag){                    try {                        System.out.println(Thread.currentThread()+"flag is true.wait@"+                                new SimpleDateFormat("HH:mm:ss").format(new Date()));                        lock.wait();                    } catch (Exception e) {                        e.printStackTrace();                    }                }                //符合条件,完成工作                System.out.println(Thread.currentThread()+"flag is true.running@"+                        new SimpleDateFormat("HH:mm:ss").format(new Date()));            }        }    }    static class Notify implements Runnable{        @Override        public void run() {            synchronized(lock){                System.out.println(Thread.currentThread()+"flag is true.Notify@"+                        new SimpleDateFormat("HH:mm:ss").format(new Date()));                lock.notifyAll();                flag=false;            }            synchronized(lock){                System.out.println(Thread.currentThread()+"flag is true.sleep@"+                        new SimpleDateFormat("HH:mm:ss").format(new Date()));            }        }    }}

等待/通知的经典范式:

等待范式:
synchronized(对象){

while(条件不满足){    对象.wait();  }对应的处理逻辑

}
通知范式:
synchronized(对象){

改变条件对象.notifyALL();

}

阅读全文
0 0
原创粉丝点击