(Java) 线程池
生活随笔
收集整理的這篇文章主要介紹了
(Java) 线程池
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線程池:1.出現版本:JDK1.52.包:java.util.concurrent3.Executors類 -->工廠類1.三個靜態方法:static ExecutorService newCachedThreadPool() 創建新的線程池對象Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.static ExecutorService newFixedThreadPool(int nThreads) 創建目標個數的線程池Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.tatic ExecutorService newSingleThreadExecutor() 創建一個線程Creates an Executor that uses a single worker thread operating off an unbounded queue.2.ExecutorService 是一個接口<T> Future<T> submit(Callable<T> task)Submits a value-returning task for execution and returns a Future representing the pending results of the task.Future<?> submit(Runnable task)Submits a Runnable task for execution and returns a Future representing that task.3.Future 是運行后的結果Callable是一個接口,call()方法有返回值public interface Callable<V>4.實現線程的三種方式:1.繼承Thead 類2.實現Runnable 接口3.實現 Callable 接口-----只要線程池支持,Thead不支持
//第一個class文件
public class RunnablePoolDemo implements Runnable{public void run(){for(int x =0;x<20;x++){System.out.println(Thread.currentThread().getName()+"run.."+x);}}
}//第二個class文件
import java.util.concurrent.Callable;/*** @author Alina* @date 2021年12月25日 11:59 下午*/
public class CallableSumDemo implements Callable<Integer> {private Integer num = 0;public CallableSumDemo(Integer num) {this.num = num;}public Integer call() {int sum = 0;for (int x = 0;x<=num;x++){sum = sum +x;}return sum;}
}//主文件package thread;import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;/*** @author Alina* @date 2021年12月25日 11:17 下午* 創建線程池* 實現方法:* 1.創建 Executors 類,靜態調用,創建兩個線程池* 3.返回對象:ExecutorService**/
public class TheadPoolDemo {public static void main(String[] args) throws Exception{method_3();}public static void method_3 () throws ExecutionException, InterruptedException {ExecutorService es3 = Executors.newFixedThreadPool(2);Future<Integer> f1 = es3.submit(new CallableSumDemo(100));Future<Integer> f2 = es3.submit(new CallableSumDemo(200));int sum1 = f1.get();int sum2 = f2.get();System.out.println(sum1);System.out.println(sum2);es3.shutdown();}public static void method_2() throws Exception{ExecutorService es2 = Executors.newFixedThreadPool(2);Future<String> ft = es2.submit(new CallablePoolDemo());String name = ft.get();System.out.println(name);}public static void method_1(){ExecutorService es = Executors.newFixedThreadPool(2);es.submit(new RunnablePoolDemo());es.submit(new RunnablePoolDemo());es.shutdown();}
}
總結
以上是生活随笔為你收集整理的(Java) 线程池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch 正向与反向传播的过程 获
- 下一篇: java美元兑换,(Java实现) 美元