/**
* 1、業(yè)務(wù)場(chǎng)景
* 1、定時(shí)執(zhí)行時(shí),可能出現(xiàn)數(shù)據(jù)量大,執(zhí)行不完,線程直接被終止掉,丟數(shù)據(jù)。
*/
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 1、首先創(chuàng)建線程池,針對(duì)線程池開啟多個(gè)線程。
* 2、for循環(huán)開始線程調(diào)用。
* 3、線程執(zhí)行完成終止掉線程。
*/
public class ForLoopMultiThreading {
public static void main(String[] args) {
// 創(chuàng)建一個(gè)ExecutorService,用于管理線程
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 創(chuàng)建一個(gè)List,用于存儲(chǔ)for循環(huán)的結(jié)果
List<Integer> resultList = new ArrayList<>();
// 定義for循環(huán)的起始和結(jié)束值
int start = 0;
int end = 100;
// 創(chuàng)建一個(gè)for循環(huán),用于計(jì)算0到100之間的所有整數(shù)
for (int i = start; i <= end; i++) {
// 將for循環(huán)的結(jié)果添加到List中
resultList.add(i);
// 提交一個(gè)任務(wù)到ExecutorService中,用于執(zhí)行for循環(huán)的每個(gè)迭代
executorService.submit(() -> {
// 在這個(gè)線程中執(zhí)行for循環(huán)
for (int j = start; j <= end; j++) {
System.out.println("Thread: " + Thread.currentThread().getName() + ", i: " + i + ", j: " + j);
}
});
}
//慎用:存在數(shù)據(jù)量大執(zhí)行不完,直接關(guān)閉線程池,數(shù)據(jù)丟失。 根據(jù)業(yè)務(wù)場(chǎng)景自定義
//如果線程內(nèi)部報(bào)錯(cuò),直接終止線程。按照定時(shí)任務(wù)執(zhí)行的,定時(shí)執(zhí)行五分鐘一次。
try {
if (!executorService.awaitTermination(300, TimeUnit.SECONDS)) {
// 如果任務(wù)在300秒內(nèi)仍未完成,強(qiáng)制關(guān)閉線程池
executorService.shutdownNow();
}
} catch (InterruptedException e) {
// 捕獲異常,并強(qiáng)制關(guān)閉線程池
executorService.shutdownNow();
e.printStackTrace();
}
// 關(guān)閉ExecutorService
executorService.shutdown();
// 輸出for循環(huán)的結(jié)果
System.out.println("Result List: " + resultList);
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-736081.html
文章來源:http://www.zghlxwxcb.cn/news/detail-736081.html
到了這里,關(guān)于java for循環(huán)內(nèi)部使用線程的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!