java 控制线程的顺序_如何实现三个线程按顺序执行?

在多线程中有多种方法让线程按特定顺序执行,可以用线程类的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();

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值