线程池
-
线程池:体检创建好多个线程,放入线程池中。使用时获取,不使用时将其丢回池中,避免重复创建销毁,实现重复利用。
-
线程池的好处
- 提高响应速度。
- 降低资源损耗
- 便于线程管理
-
线程的创建
- 线层使用ExecutorService接口创建线程,通过Executors.newFixedThreadPool确定线程池大小。
eg:创建一个大小为10 的线程池:ExecutorService executorService= Executors.newFixedThreadPool(10);
- 线程的运行:
executorService.execute(线程);
- 线程池的关闭:
executorService.shutdown();
- 线层使用ExecutorService接口创建线程,通过Executors.newFixedThreadPool确定线程池大小。
-
完整代码例子:
package com.XianCheng.ImportPort;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//线程池的使用
public class ThreadS {
public static void main(String[] args) {
//1.创建服务,创建线层池
ExecutorService executorService= Executors.newFixedThreadPool(10);
//运行线程
executorService.execute(new test());
executorService.execute(new test());
executorService.execute(new test());
executorService.execute(new test());
//关闭线程池
executorService.shutdown();
}
}
//创建线程
class test implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"创建成功");
}
}