Java实现两个线程交替打印奇偶数

使用两个线程分别交替打印奇偶数。

实现思路,通过一个对象锁同步请求,获取锁之后判断当前数字时候为奇数或者偶数,然后使用Object.wait方法释放锁并等待。

 


public class Main {

    public static void main(String[] args) {

        Main main = new Main();
        main.test();
    }

    private volatile int count = 0;
    public class Thread1 extends Thread {
        private final Object obj;
        public Thread1(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (obj) {
                    if (count % 2 == 1) {
                        System.out.println("thread1: " + count);
                        count++;
                    }
                    try {
                        obj.notifyAll();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count > 1000) {
                        return;
                    }
                }
            }
        }
    }

    public class Thread2 extends Thread {
        private final Object obj;
        public Thread2(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (obj) {
                    if (count % 2 == 0) {
                        System.out.println("thread2: " + count);
                        count++;
                    }
                    try {
                        obj.notifyAll();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (count > 1000) {
                        return;
                    }
                }
            }
        }
    }

    public void test() {
        Object obj = new Object();
        Thread t1 = new Thread1(obj);
        Thread t2 = new Thread2(obj);

        t1.start();
        t2.start();
    }
}

输出结果

Java实现两个线程交替打印奇偶数_第1张图片

你可能感兴趣的:(java)