线程池: API: ExecutorService(线程池接口) Executors(线程池的工厂类 用于创建并返回不同类型的线程池) 方法: void execute(Runnable command): 无返回值 一般用来执行Runnable接口的实现类的线程 <T> Future<T> submit(Callable<T> task): 有返回值 一般用来执行Callable接口的实现类的线程
创建线程池
ExecutorService service = Executors.newFixedThreadPool(int nThreads);
关闭线程池
service.shutdown();
线程池实例一:线程类实现Runnable接口
public class TestPool {
public static void main(String[] args) {
//1.创建服务 创建线程池(参数为线程池大小)
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
运行效果
线程池实例二:线程类实现Callable接口
public class Test {
public static void main(String[] args) {
TestThread testThread01 = new TestThread("testThread01");
TestThread testThread02 = new TestThread("testThread02");
TestThread testThread03 = new TestThread("testThread03");
//创建执行服务(线程池)
ExecutorService service = Executors.newFixedThreadPool(10);
//提交执行 并通过Future<Boolean>接收返回值
Future<Boolean> result01 = service.submit(testThread01);
Future<Boolean> result02 = service.submit(testThread02);
Future<Boolean> result03 = service.submit(testThread03);
//获取返回值
try {
boolean getReturn01 = result01.get();
boolean getReturn02 = result02.get();
boolean getReturn03 = result03.get();
//输出返回值
System.out.println(getReturn01);
System.out.println(getReturn02);
System.out.println(getReturn03);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
//关闭服务
service.shutdown();
}
}
}
class TestThread implements Callable<Boolean> {
String currentThreadName;
public TestThread(String currentThreadName) {
this.currentThreadName = currentThreadName;
}
@Override
public Boolean call() throws Exception {
System.out.println(currentThreadName);
return true;
}
}
运行效果