Java多线程控制交替输出1和2

2017-02-21  本文已影响118人  zhangxuanchen
    public static void main(String[] args) {
        AtomicBoolean m = new AtomicBoolean();
        m.set(true);
        System.out.println("AtomicBoolean:" + m.get());
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.setMain(m);
        thread2.setMain(m);
        thread1.start();
        thread2.start();
        
    }
    
    static class Thread1 extends Thread{
        AtomicBoolean m ;
        public void setMain(AtomicBoolean m){
            this.m = m;
        }
        
        @Override
        public void run() {
            while(true){
                    try {
                        synchronized (m) {
                            System.out.println("tag1:" + m.get());
                            if(m.get()){
                                System.out.println("1");
                                m.set(false);
                                m.notify();
                            }
                            m.wait();
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
        }
    }
    
    static class Thread2 extends Thread{
        AtomicBoolean m ;
        public void setMain(AtomicBoolean m){
            this.m = m;
        }
        @Override
        public void run() {
            while(true){
                    try {
                        synchronized (m) {
                            System.out.println("tag2:" + m.get());
                            if(!m.get()){
                                System.out.println("2");
                                m.set(true);
                                m.notify();
                            }
                            m.wait();
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读