代碼
import lombok.Data;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MyTest {
public static void main(String[] args) {
long l = System.currentTimeMillis();
// 創(chuàng)建閉鎖,需執(zhí)行3個線程
CountDownLatch countDownLatch = new CountDownLatch(3);
// 線程1,計算 3 * 3,需執(zhí)行1s
Para para1 = new Para(3);
ExecutorService thread1 = Executors.newSingleThreadExecutor();
thread1.execute(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
para1.setA(para1.getA() * para1.getA());
countDownLatch.countDown();
});
// 線程2片效,計算 4 * 4梗脾,需執(zhí)行3s
Para para2 = new Para(4);
ExecutorService thread2 = Executors.newSingleThreadExecutor();
thread2.execute(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
para2.setA(para2.getA() * para2.getA());
countDownLatch.countDown();
});
// 線程3,計算 5 * 5投储,需執(zhí)行6s
Para para3 = new Para(5);
ExecutorService thread3 = Executors.newSingleThreadExecutor();
thread3.execute(() -> {
try {
Thread.sleep(6000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
para3.setA(para3.getA() * para3.getA());
countDownLatch.countDown();
});
// 三個線程執(zhí)行完畢或超過后,繼續(xù)執(zhí)行阔馋,并關閉所有線程
boolean await = false;
try {
// 超時時間4s
await = countDownLatch.await(4L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 關閉所有線程
thread1.shutdown();
thread2.shutdown();
thread3.shutdown();
}
// 判斷是否全部執(zhí)行成功
if (await) {
System.out.println("執(zhí)行成功玛荞,耗時:" + (System.currentTimeMillis() - l));
} else {
System.out.println("執(zhí)行超時,部分執(zhí)行失敗呕寝,耗時:" + (System.currentTimeMillis() - l));
}
// 計算結果
System.out.println(para1);
System.out.println(para2);
System.out.println(para3);
}
}
@Data
class Para {
private Integer a;
public Para(Integer a) {
this.a = a;
}
@Override
public String toString() {
return "Para [" +
"a=" + a +
']';
}
}
執(zhí)行結果
超時時間設為10s時
image.png
超時時間設置為4s時
image.png
拓展
這里的示例是3個線程并行執(zhí)行勋眯,拿到3個線程的執(zhí)行結果。
image.png
如果想實現(xiàn)更復雜的線程聯(lián)排下梢,可直接在代碼后面追加鏈路客蹋。
image.png
如果還需要更加復雜的組合的話可以使用京東的開源框架
asyncTool