两线程实现奇偶交替打印

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_38201936/article/details/100270860

两种方式实现:

1 通过wait()/notifyall()方法实现

/*
两条线程实现交替打印奇偶数
 */
public class ThreadExchange {

    private static Object lock = new Object();

    private static int i = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread1());
        Thread t2 = new Thread(new Thread2());
        t1.start();
        t2.start();
    }

    static class  Thread1 implements Runnable{
        @Override
        public void run() {
            while (i<=100){
                synchronized (lock){
                    if (i%2==1){
                        System.out.println("Thread1  " + i++);
                    }else {
                        lock.notifyAll();
                        try {
                            lock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    static class  Thread2 implements Runnable{
        @Override
        public void run() {
            while (i<=100){
                synchronized (lock){
                    if (i%2==0){
                        System.out.println("Thread2  " + i++);
                    }else {
                        lock.notifyAll();
                        try {
                            lock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

2 通过volatile+自旋锁实现

public class ThreadExchange1 {
    private static volatile int i = 1;
    public static void main(String[] args) {
        new Thread(new PrintRunner(1),"ji shu").start();
        new Thread(new PrintRunner(0),"ou shu").start();

    }
    static class PrintRunner implements Runnable{
        private int result;
        public PrintRunner(int i) {result = i;}
        @Override
        public void run() {
            while(i < 10){
                // 据说用除余运算也一样,因为编译器优化过了
                if((i & 1) == result){
                    System.out.println(Thread.currentThread().getName() + i);
                    // 这里必须要在打印完后进行加操作
                    i++;
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38201936/article/details/100270860