有序打印线程

1、使用Thread.join()方法

thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B

public class ThreadTest1 {
   
    public static void main(String[] args) {
   
        Thread t1 = new Thread(new Work(null));
        Thread t2 = new Thread(new Work(t1));
        Thread t3 = new Thread(new Work(t2));
        t1.setName("第一个");
        t2.setName("第二个");
        t3.setName("第三个");
        t1.start();
        t2.start();
        t3.start();
    }
    static class Work implements Runnable {
   
        private Thread thread;
        public Work(Thread thread) {
   
            this.thread = thread;
        }
        @Override
        public void run() {
   
            if (thread != null) {
   
                try {
   
                    thread.join();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
                execute();
            } else {
   
                execute();
            }
        }
        private void execute() {
   
            System.out.println("线程" + Thread.currentThread().getName() + "执行");
        }
    }
}

<mark>第三种</mark>:用线程池的队列来执行任务

<mark>第三种</mark>:用公共锁Object,配合wait/notifyAll方法,睡眠自己,唤醒另一个线程~

参考链接[https://www.javazhiyin.com/42563.html]