两个线程交替打印奇偶数

时间:2021-09-07 00:53:26   收藏:0   阅读:28
public class Thtest {
    private static final Object obj = new Object();
    public static void main(String[] args) {

        new Thread(new Runnable(){

            @Override
            public void run() {
                for(int i = 0;i<100;i++){
                    synchronized (obj){
                        if ((i & 1) == 1){
                            System.out.println(Thread.currentThread().getName()+":"+i);
                        }
                        obj.notify();
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        },"奇数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++){
                    synchronized (obj){
                        if ((i&1)==0){
                            System.out.println(Thread.currentThread().getName()+":"+i);
                        }
                        obj.notify();
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"偶数线程").start();
    }
}

 

原文:https://www.cnblogs.com/Dkfeng/p/15235014.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!