zoukankan      html  css  js  c++  java
  • java线程 WaitAndNotify

    wait  方法会使持有该对象的线程把该对象的控制权交出去,然后处于等待状态。

    notify 方法会通知某个正在等待这个对象的控制权的线程继续运行。

    notifyAll 方法会通知所有正在等待这个对象的控制权的线程继续运行

    注意:一定要在线程同步中使用,并且是同一个锁的资源 

    public class Demo7WaitAndNotify {
        public static void main(String[] args) {
            State state = new State();
            InThread inThread = new InThread(state);
            OutThread outThread = new OutThread(state);
    
            Thread in = new Thread(inThread);
            Thread out = new Thread(outThread);
    
            in.start();
            out.start();
        }
    
        // 控制状态
        static class State {
            //状态标识
            public String flag = "车站外";
        }
    
        static class InThread implements Runnable {
            private State state;
    
            public InThread(State state) {
                this.state = state;
            }
    
            public void run() {
                while (true) {
                    synchronized (state) {
                        if ("车站内".equals(state.flag)) {
                            try {
                                // 如果在车站内,就不用进站,等待,释放锁
                                state.wait();
                            } catch (Exception e) {
                            }
                        }
    
                        System.out.println("进站");
                        state.flag = "车站内";
                        // 唤醒state等待的线程
                        state.notify();
                    }
                }
            }
        }
    
        static class OutThread implements Runnable {
            private State state;
    
            public OutThread(State state) {
                this.state = state;
            }
    
            public void run() {
                while (true) {
                    synchronized (state) {
                        if ("车站外".equals(state.flag)) {
                            try {
                                // 如果在车站外,就不用出站了,等待,释放锁
                                state.wait();
                            } catch (Exception e) {
                            }
                        }
                        System.out.println("出站");
                        state.flag = "车站外";
                        // 唤醒state等待的线程
                        state.notify();
                    }
                }
            }
        }
    }
  • 相关阅读:
    Cron表达式说明
    exe4j 使用记录(二):jar打包exe
    exe4j 使用记录(一):下载、安装及注册
    Sublime Text3添加右键
    jenkins 入门教程
    Visual Studio设置字体及护眼背景色
    Visual Studio 设置C#语言代码格式
    Visual Studio 常用快捷键
    Maven中使用本地JAR包
    oracle 查看锁表及解锁的语句
  • 原文地址:https://www.cnblogs.com/angdh/p/15564577.html
Copyright © 2011-2022 走看看