Java多线程利用synchronized交替打印奇数和偶数

问题:
java面试中经常会遇到这个问题,如何用两个线程交替打印奇偶数。线程A打印1,线程B打印2。我们常用的实现方式是采用wait/notifyAll方法。
思路:
要两个线程交替打印奇偶数,必须让两个线程共享一个count,当数字是奇数是线程A打印,当数字是偶数时线程B打印,执行完打印操作后自增count,并利用wait/notifyAll方法去阻塞和唤醒线程。

代码如下:

public class PrintNumber {
    static class Wrapper {
        private int count;
        public Integer getCount() {
            return count;
        }
        public void setCount(Integer count) {
            this.count = count;
        }
    }
    static class PrintOdd implements Runnable{
        private Wrapper wrapper;
        public PrintOdd(Wrapper wrapper){
            this.wrapper = wrapper;
        }

        @Override
        public void run() {
            try {
                synchronized (wrapper){
                    while (wrapper.getCount() <= 100){
                        if (wrapper.getCount() % 2 == 0){
                            wrapper.wait();
                        }else {
                            System.out.println(Thread.currentThread().getName() + "PrintOdd" + wrapper.getCount());
                            wrapper.setCount(wrapper.getCount() + 1);
                            wrapper.notifyAll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    static class PrintEven implements Runnable{
        private Wrapper wrapper;
        public PrintEven(Wrapper wrapper){
            this.wrapper = wrapper;
        }

        @Override
        public void run() {
            try {
                synchronized (wrapper){
                    while (wrapper.getCount() <= 100){
                        if (wrapper.getCount() % 2 == 1){
                            wrapper.wait();
                        }else {
                            System.out.println(Thread.currentThread().getName() + "PrintEven" + wrapper.getCount());
                            wrapper.setCount(wrapper.getCount() + 1);
                            wrapper.notifyAll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Wrapper wrapper = new Wrapper();//必须共用一个Wrapper对象
        PrintOdd odd = new PrintOdd(wrapper);
        PrintEven even = new PrintEven(wrapper);
        new Thread(odd).start();
        new Thread(even).start();
    }
}

你可能感兴趣的:(基础编程)