线程学习 两个线程交替打印奇偶数

/**
 * @author: 刘磊
 * @Description: 交替打印奇偶数
 * @date: 2019/3/26 14:07
 **/
public class Test {
    static class NUM{
        int i = 0;
    }
    static NUM num = new NUM();
    @org.junit.Test
    public void test(){
        new Thread(new Tread() ,"奇数线程").start();
        new Thread(new Tread() ,"偶数线程").start();;
    }
    static class Tread implements Runnable{
        @Override
        public void run() {
            while (num.i<=10){
                synchronized (num){
                    if(num.i<=10){
                        //判断num里值的奇偶
                        if((num.i&1)==1){
                            if(Thread.currentThread().getName().equals("奇数线程")){
                                System.out.println(Thread.currentThread().getName()+":"+ num.i);
                                num.i++;
                            }
                        }else {
                            if(Thread.currentThread().getName().equals("偶数线程")){
                                System.out.println(Thread.currentThread().getName()+":"+ num.i);
                                num.i++;
                            }
                        }
                    }
                }
            }
        }
    }
}

 

你可能感兴趣的:(线程学习 两个线程交替打印奇偶数)