日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Java多线程,Thread,Runnable,Callable Task,Future<Task>,CompletionService

發(fā)布時(shí)間:2023/11/27 生活经验 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java多线程,Thread,Runnable,Callable Task,Future<Task>,CompletionService 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、Java多線程的方法

1. 繼承 Thread
2. 實(shí)現(xiàn) Runnable
3. 實(shí)現(xiàn) Callable 可以有返回值

package com.test;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;class MyTread extends Thread {public void run() {System.out.println(Thread.currentThread().getName());}
}//實(shí)現(xiàn)Runable接口,實(shí)現(xiàn)run方法;
class MyRunnable implements Runnable {public void run() {System.out.println(Thread.currentThread().getName());}
}class MyCallable implements Callable<String> {private List<String> ids;public MyCallable(List<String> ids) {this.ids = ids;}@Overridepublic String call() throws Exception {// 獲取參數(shù),執(zhí)行響應(yīng)的操作for (String id : ids) {// 此處為對(duì)數(shù)據(jù)的操作System.out.println(id);}// 返回改線程的idreturn Thread.currentThread() + "";}
}public class ThreadTest {public static void main(String[] args) throws Exception {MyTread thread = new MyTread();thread.start(); //開啟一個(gè)線程MyRunnable myRunnable = new MyRunnable();Thread runnable = new Thread(myRunnable);runnable.start(); //開啟一個(gè)線程MyCallable myCallable = new MyCallable(new ArrayList<>());String res = myCallable.call(); // 開啟一個(gè)線程System.out.println("res: " + res);}
}

Java多線程,一種是不需要等待結(jié)果,一種是需要等待任務(wù)執(zhí)行完成的結(jié)果,在執(zhí)行相關(guān)操作。下邊著重介紹第二種;

二、等待執(zhí)行結(jié)果返回在執(zhí)行后續(xù)操作

(1)Future類,Future ExecutorService futureTasks.get(i).get()會(huì)阻塞,直到線程執(zhí)行完有所返回值
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;class MyCallables implements Callable<Integer> {private int num;private String name;public MyCallables(Integer num, String name) {this.num = num;this.name = name;}@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i < num; i = i + 100) {sum += i;}System.out.println("\t---: " + System.currentTimeMillis() + " " + this.name);Thread.sleep(num / 100);System.out.println("\t---: " + System.currentTimeMillis() + " " + this.name);return sum;}
}@Slf4j
@Component
public class TestThreadWork {public static void main(String[] args) throws Exception {int[] numArr = new int[]{100, 200, 300, 400, 500};long start = System.currentTimeMillis();List<FutureTask<Integer>> futureTasks = new ArrayList<>();for (Integer num : numArr) {// 創(chuàng)建線程處理MyCallables callable = new MyCallables(num, "thread-" + String.valueOf(num));FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);futureTasks.add(futureTask);}//創(chuàng)建線程池后,依次提交任務(wù),執(zhí)行ExecutorService executorService = Executors.newCachedThreadPool();for (FutureTask<Integer> futureTask : futureTasks) {executorService.submit(futureTask);}executorService.shutdown();//根據(jù)任務(wù)數(shù),依次去獲取任務(wù)返回的結(jié)果,獲取結(jié)果時(shí)會(huì)依次返回,若前一個(gè)沒返回,則會(huì)等待,阻塞for (int i = 0; i < numArr.length; i++) {int sum = futureTasks.get(i).get();System.out.println("sum: " + sum);}log.info("timeConsumer: {}", (System.currentTimeMillis() - start));}
}
(2)ExecutorService、CompletionService pool.take().get(),同樣會(huì)阻塞,直到線程執(zhí)行完返回值

https://blog.csdn.net/qq_36898043/article/details/79733124

(3)countDownLatch 閉鎖
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;/************************************** Class Name: TestCountDownLatch* Description:〈測(cè)試countDownLatch鎖🔒〉* @create 2020/8/25* @since 1.0.0************************************/
public class TestCountDownLatch {public static void main(String[] args) {// 創(chuàng)建線程池int[] numArr = new int[]{100, 200, 300, 400, 500};final CountDownLatch countDownLatch = new CountDownLatch(numArr.length);List<Future<Integer>> futureList = new ArrayList<>();ExecutorService executorService = Executors.newCachedThreadPool();for (int num : numArr) {Future<Integer> future = executorService.submit(new Callable<Integer>() {@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i < num; i++) {sum += num;}countDownLatch.countDown();return sum;}});// 提交任務(wù)futureList.add(future);}try {// 等待所有線程執(zhí)行完畢countDownLatch.await();Integer totalCount = 0;for (Future<Integer> future : futureList) {totalCount += future.get();}System.out.println("--------totalCount: " + totalCount);} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} finally {if (executorService.isShutdown()) {return;}executorService.shutdown();}}
}
參考:
  • http://quanzhan.applemei.com/webStack/TXpRNE13PT0=

  • https://blog.csdn.net/qq_36898043/article/details/79733124

總結(jié)

以上是生活随笔為你收集整理的Java多线程,Thread,Runnable,Callable Task,Future<Task>,CompletionService的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。