1、FixedThreadPool
固定容量的线程池,线程池默认的容量上限是Integer.MAX_VALUE。常见的线程池容量:pc=200,服务器=1000~10000
FixedThreadPool一般由Executors(工具类)来获取,并可以指定线程池的容量。线程池是一个进程级的重量级资源。默认的生命周期和JVM一致。当开启线程池后,知道JVM关闭为止,是线程池的默认生命周期。可以通过调用shutdown方法来让线程池执行完所有的任务后,自动关闭。
Executor是线程池顶级接口,定义了execute(Runnable) 方法。调用的时候提供Runnable的实现,线程池通过这个线程去执行这个Runnable。
ExecutorService是Executro的子接口。
下面的代码定义了具有5个线程的线程池,初始化6个线程去运行任务,shutdown并不是马上关闭,是等到线程池中的任务执行结束后再关闭
package com.sunyou.p5;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/*
* 容量固定的线程池。活动状态和线程池容量是有上限的线程池。
* 所有的线程池中,都有一个任务队列。
* 使用的是 BlockingQueue<Runnable>作为任务的载体。
* 当任务数量大于线程池容量的时候,没有运行的任务保存在任务队列中,当线程有空闲的,自动从队列中取出任务执行
*
* 常见的线程池容量 pc-20 服务器 1000-10000
*/
public class FixedThreadPoolTest {
private static ExecutorService service = Executors.newFixedThreadPool(5);
public static void main(String[] args) throws Exception {
for(int i = 0; i < 6; i++) {
service.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"正在执行");
}
});
}
System.out.println(service);//service如果不关,程序会一直运行
System.out.println(service.isShutdown());
System.out.println(service.isTerminated());
service.shutdown();
TimeUnit.SECONDS.sleep(2);
System.out.println(service);
System.out.println(service.isShutdown());
System.out.println(service.isTerminated());
}
}
运行结果
pool-1-thread-1正在执行
pool-1-thread-5正在执行
pool-1-thread-1正在执行
pool-1-thread-4正在执行
pool-1-thread-3正在执行
pool-1-thread-2正在执行
java.util.concurrent.ThreadPoolExecutor@42a57993[Running, pool size = 5, active threads = 1, queued tasks = 0, completed tasks = 5]
false
false
java.util.concurrent.ThreadPoolExecutor@42a57993[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]
true
true
2、Future
未来结果,代表线程任务执行结束后的结果。获取线程执行结果的方式是通过get方法获取。该方法会阻塞等待线程执行结束,并得到返回结果。如果该方法传入参数,阻塞固定时长,等待线程执行结束后的结果,如果等待过程中线程未执行结束会抛出异常。
package com.sunyou.p6;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class FutureTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(1);
Future<String> future = service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("call method is start");
TimeUnit.SECONDS.sleep(1);
return Thread.currentThread().getName()+" is over";
}
});
System.out.println(future);
System.out.println(future.isDone());
System.out.println("future的返回值为 "+future.get());
System.out.println(future.isDone());
}
}
执行结果
java.util.concurrent.FutureTask@33909752
call method is start