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();
                    }
                }
            }
        }
    }
  • 相关阅读:
    202011051 每周例行报告
    202011261 每周例行报告
    202010153 每周例行报告
    keil代码定位
    VC2008创建MFC工程遇到的问题及解决方法
    面朝大海, 春暖花
    Oracle10G数据库教程
    郁闷来了
    MPEG4与.mp4
    vs2003 使用ffmpeg,sdl时的编译问题
  • 原文地址:https://www.cnblogs.com/angdh/p/15564577.html
Copyright © 2011-2022 走看看