java 并发 两个线程交替打印 奇数偶数


public class Service {

    private final Object lock = new Object();

    private int odd = -1;
    private int even = -2;
    /* 线程启动先后顺序无法预料,最后启动的线程释放锁,执行notify  */
    private int first_start_odd = 0;
    private int first_start_even = 0;

    private void print_odd() {
        System.out.println("entry print_odd()");

        while (odd < 100) {
            synchronized (lock) {

                if (first_start_odd == 0) {

                    lock.notify();
                    first_start_odd += 1;
                }

                try {

                    lock.wait();
                    System.out.println("奇数:" + (odd += 2));
                    Thread.sleep(50);

                    lock.notify();

                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }
    }

    private void print_even() {
        System.out.println("entry print_even()");
        while (even < 100) {

            synchronized (lock) {
                if (first_start_even == 0) {

                    lock.notify();
                    first_start_even += 1;
                }

                try {
                    lock.wait();
                    System.out.println("偶数:" + (even += 2));
                    Thread.sleep(50);

                    lock.notify();

                } catch (Exception e) {


                }
            }
        }
    }


    public static void main(String[] args) {
        final Service se = new Service();


        new Thread(new Runnable() {

            public void run() {
                se.print_even();

            }
        }).start();

        new Thread(new Runnable() {

            public void run() {
                se.print_odd();

            }
        }).start();


    }


}
发布了42 篇原创文章 · 获赞 35 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/wang603603/article/details/89349881