线程池:
1.出现版本:JDK1.5
2.包:java.util.concurrent
3.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();
}
}
|