
下面由java入門程式欄位為大家介紹如何在java中讓執行緒順序執行,希望對大家有幫助!
我們需要完成這樣一個應用場景:
1.早上;2.測試人員、產品經理、開發人員陸續的來公司上班;3.產品經理規劃新需求;4.開發人員開發新需求功能;5.測試人員測試新功能。
規劃需求,開發需求新功能,測試新功能是一個有順序的,我們把thread1看做產品經理,thread2看做開發人員,thread3看做測試人員。
使用執行緒的join 方法
join():是Theard的方法,作用是呼叫執行緒需等待該join()執行緒執行完成後,才能繼續使用下運行。
應用場景:當一個執行緒必須等待另一個執行緒執行完畢才能執行時可以使用join方法。
實例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | package com.zhangsf.javabase.thread.order;
public class ThreadJoinDemo {
public static void main(String[] args) {
final Thread thread1 = new Thread( new Runnable() {
@Override
public void run() {
System.out.println( "产品经理规划新需求" );
}
});
final Thread thread2 = new Thread( new Runnable() {
@Override
public void run() {
try {
thread1.join();
System.out.println( "开发人员开发新需求功能" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread3 = new Thread( new Runnable() {
@Override
public void run() {
try {
thread2.join();
System.out.println( "测试人员测试新功能" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println( "早上:" );
System.out.println( "测试人员来上班了..." );
thread3.start();
System.out.println( "产品经理来上班了..." );
thread1.start();
System.out.println( "开发人员来上班了..." );
thread2.start();
}
}
|
登入後複製
執行結果:

使用主執行緒的join 方法
這裡是在主執行緒中使用join()來實現對執行緒的阻塞。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.zhangsf.javabase.thread.order;
public class ThreadMainJoinDemo {
public static void main(String[] args) throws Exception {
final Thread thread1 = new Thread( new Runnable() {
@Override
public void run() {
System.out.println( "产品经理正在规划新需求..." );
}
});
final Thread thread2 = new Thread( new Runnable() {
@Override
public void run() {
System.out.println( "开发人员开发新需求功能" );
}
});
final Thread thread3 = new Thread( new Runnable() {zzzz
@Override
public void run() {
System.out.println( "测试人员测试新功能" );
}
});
System.out.println( "早上:" );
System.out.println( "产品经理来上班了" );
System.out.println( "测试人员来上班了" );
System.out.println( "开发人员来上班了" );
thread1.start();
System.out.println( "开发人员和测试人员休息会..." );
thread1.join();
System.out.println( "产品经理新需求规划完成!" );
thread2.start();
System.out.println( "测试人员休息会..." );
thread2.join();
thread3.start();
}
}
|
登入後複製
運行結果:

讓執行緒順序執行的方法還有很多,以後會為大家一一介紹。
以上是java中如何讓執行緒順序執行的詳細內容。更多資訊請關注PHP中文網其他相關文章!