base - thread - 如何顺序打印出线程对应的序号

56 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

public class Test2 {

    private static volatile int ii = 0;
    private static final Object o = new Object();

    public static void main(String[] args) throws InterruptedException {

        int n = 5;
        for (int i=0; i<n; i++) {
            new ThreadTest(i).start();
        }
    }

    static class ThreadTest extends Thread {
        private final Integer num;
        public ThreadTest(int num) {
            this.num = num;
        }

        @Override
        public void run() {
            synchronized (o) {
                while (ii < 5) {
                    if (num != ii) {
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("Thread - " + ii);
                        ii++;
                        o.notifyAll();
                    }
                }
            }
        }
    }
}
  1. notifyAll和wait成对出现
  2. 在没有输出完所有线程之前需要一直比较 - while