Java多线程,Thread,Runnable,Callable Task,Future<Task>,CompletionService
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Java多线程,Thread,Runnable,Callable  Task,Future<Task>,CompletionService
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                一、Java多線程的方法
1. 繼承 Thread
 2. 實現 Runnable
 3. 實現 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());}
}//實現Runable接口,實現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 {// 獲取參數,執行響應的操作for (String id : ids) {// 此處為對數據的操作System.out.println(id);}// 返回改線程的idreturn Thread.currentThread() + "";}
}public class ThreadTest {public static void main(String[] args) throws Exception {MyTread thread = new MyTread();thread.start(); //開啟一個線程MyRunnable myRunnable = new MyRunnable();Thread runnable = new Thread(myRunnable);runnable.start(); //開啟一個線程MyCallable myCallable = new MyCallable(new ArrayList<>());String res = myCallable.call(); // 開啟一個線程System.out.println("res: " + res);}
}
Java多線程,一種是不需要等待結果,一種是需要等待任務執行完成的結果,在執行相關操作。下邊著重介紹第二種;
二、等待執行結果返回在執行后續操作
(1)Future類,Future ExecutorService futureTasks.get(i).get()會阻塞,直到線程執行完有所返回值
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) {// 創建線程處理MyCallables callable = new MyCallables(num, "thread-" + String.valueOf(num));FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);futureTasks.add(futureTask);}//創建線程池后,依次提交任務,執行ExecutorService executorService = Executors.newCachedThreadPool();for (FutureTask<Integer> futureTask : futureTasks) {executorService.submit(futureTask);}executorService.shutdown();//根據任務數,依次去獲取任務返回的結果,獲取結果時會依次返回,若前一個沒返回,則會等待,阻塞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(),同樣會阻塞,直到線程執行完返回值
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:〈測試countDownLatch鎖🔒〉* @create 2020/8/25* @since 1.0.0************************************/
public class TestCountDownLatch {public static void main(String[] args) {// 創建線程池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;}});// 提交任務futureList.add(future);}try {// 等待所有線程執行完畢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 
總結
以上是生活随笔為你收集整理的Java多线程,Thread,Runnable,Callable Task,Future<Task>,CompletionService的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Linux(Nginx)+Java Sp
- 下一篇: .pgr照片文件解析,C++与Java存
