1 线程池
- 提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁的额外开销,提高了响应速度
2 线程池的体系结构
![Executor体系结构](https://i-blog.csdnimg.cn/blog_migrate/a464930ebf6c7d026d2cf0e600262a2a.jpeg)
3 工具类:Excutors
方法名 | 方法解释 |
---|
newFixedThreadPool(int 线程数) | 创建固定大小的线程池 |
newCachedThreadPool() | 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量 |
newSingleThreadExecutor() | 创建单个线程池,线程池中只有一个线程 |
newScheduledThreadPool() | 创建固定大小的线程,可以延迟或定时的执行任务 |
package JUC;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThreadPools {
public static void main(String[] args) {
test02();
}
public static void test01() {
// 创建固定大小的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(5);
ThreadDemo6 demo = new ThreadDemo6();
for (int i = 0; i < 10; i++) {
// 注入任务
threadPool.submit(demo);
}
// 等待线程的任务结束后关闭该线程
threadPool.shutdown();
// 没有条件的直接关闭线程,不推荐使用
// threadPool.shutdownNow();
}
public static void test02() {
ExecutorService threadPool = Executors.newFixedThreadPool(5);
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
}
});
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
}
threadPool.shutdown();
}
}
class ThreadDemo6 implements Runnable {
private int i = 0;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " i = " + i);
}
}
}
4 线程调度
schedule()
方法的参数
- 参数一:
Callable
的任务 - 参数二:多长时间执行一次(int型)
- 参数三:
TimeUnit
的时间单位(SECONDS
等)
package JUC;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 5; i++) {
Future future = threadPool.schedule(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(100);
System.out.print(Thread.currentThread().getName() + " : ");
return num;
}
}, 1, TimeUnit.SECONDS);
System.out.println(future.get());
}
threadPool.shutdown();
}
}