在多线程中有多种方法让线程按特定顺序执行,可以用线程类的join()方法在一个线程中启动另一个线程,另外一个线程完成该线程继续执行。
为了确保三个线程的顺序你应该先启动最后一个(T3调用T2,T2调用T1),这样T1就会先完成而T3最后完成。实际上先启动三个线程中哪一个都行,因为在每个线程的run方法中用join方法限定了三个线程的执行顺序。
实例一
public static void main(String[] args) { final Thread t1 = new Thread(() -> System.out.println("A")); final Thread t2 = new Thread(() -> { try { // 引用t1线程,等待t1线程执行完 t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("B"); }); Thread t3 = new Thread(() -> { try { // 引用t2线程,等待t2线程执行完 t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("C"); }); t3.start();//这里三个线程的启动顺序可以任意 t2.start(); t1.start(); } t1 t2 t3
实例二
public static class T1 implements Runnable { @Override public void run() { new Thread(new T2()).start(); System.out.println("A"); } } public static class T2 implements Runnable { @Override public void run() { new Thread(new T3()).start(); System.out.println("B"); } } public static class T3 implements Runnable { @Override public void run() { System.out.println("C"); } } public static void main(String[] args) { new Thread(new T1()).start(); }
实例三
public static class T1 extends Thread { @Override public void run() { System.out.println("A"); } } public static class T2 extends Thread { @Override public void run() { System.out.println("B"); } } public static class T3 extends Thread { @Override public void run() { System.out.println("C"); } } public static void main(String[] args) throws Exception{ T1 t1 = new T1(); T2 t2 = new T2(); T3 t3 = new T3(); t1.start(); t1.join(); t2.start(); t2.join(); t3.start(); t3.join(); }
未经允许请勿转载:程序喵 » 如何实现三个线程按顺序执行?