- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- System.out.println("t1");
- }
- });
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- //引用t1线程,等待t1线程执行完
- t1.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("t2");
- }
- });
- Thread t3 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- //引用t2线程,等待t2线程执行完
- t2.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("t3");
- }
- });
- t3.start();
- t2.start();
- t1.start();
假如有三个线程T1,T2,T3,如何保证T2在T3之前执行完成,T1在T2之前完成?
使用join方法,在本线程中引用需要加入进来执行的线程,这样来确保加入进来的线程可以先执行。