码迷,mamicode.com
首页 > 编程语言 > 详细

2个线程A-B-A-B或者B-A-B-A循环输出

时间:2018-04-06 22:36:26      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:inter   runnable   分享   png   代码   stack   private   循环输出   sleep   

代码:

/**
 * 两个线程循环打印输出a-b-a-b
 */
public class AandBforTOthread {
    private static Object o = new Object();
    private static int flag=0;
    private static boolean close=false;
    static class A implements Runnable {
        @Override
        public void run() {
            synchronized (o) {
                if (flag==0){
                    flag=1;
                }
                while (!close) {
                    System.out.println("A");
                    if (flag==1){
                        try {
                            o.wait();//释放锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        o.notify();
                    }else {
                        o.notify();
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
                o.notify();
            }
        }
    }

    static class B implements Runnable {
        @Override
        public void run() {
            if (flag==0){
                flag=2;
            }
            synchronized (o) {
                while (!close) {
                    System.out.println("B");
                    if (flag==1){
                        o.notify();
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        try {
                            o.wait();//释放锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        o.notify();
                    }
                }
                o.notify();
            }
        }
    }

    public static void main(String[] args) {
        Thread a = new Thread(new A());
        Thread b = new Thread(new B());
        b.start();
        a.start();
        try {
            Thread.sleep(10l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        close=true;
        a.interrupt();
        b.interrupt();
    }
}

  输出:技术分享图片技术分享图片

 

2个线程A-B-A-B或者B-A-B-A循环输出

标签:inter   runnable   分享   png   代码   stack   private   循环输出   sleep   

原文地址:https://www.cnblogs.com/qfxydtk/p/8728877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!