如何确保线程在调用thread.start()之后立即启动 - Java

时间:2017-11-05 15:38:33

标签: java multithreading

        int n = 10;
        Object lock = new Object();
        Thread odd = new Thread(() -> {
            for (int i = 1; i < n; i+=2) {
                synchronized (lock) {
                    System.out.println("odd " + i);
                    lock.notify();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread even = new Thread(() -> {
               //bookmark line
            for (int i = 0; i < n; i+=2) {
                synchronized (lock) {
                    System.out.println("even " + i);
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.notify();
                }
            }
        });
        even.start();
        odd.start();

这个程序工作得很好,打印甚至奇数。但我的问题是因为线程调度程序,我的奇数线程有可能在偶数线程之前启动。我如何确保偶数线程总是在奇数线程之前开始?

2 个答案:

答案 0 :(得分:-1)

廉价解决方案是在开始循环之前睡眠奇数线程500毫米

答案 1 :(得分:-1)

put&#39; odd.start();&#39;在偶数线程内