线程池
1. 线程池概念
2. 标准库线程池 (面试考点)
总结:
3. 工厂类创建线程池和基本使用
查看代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Test {
public static void main(String[] args) {
// 1. 能够根据任务的数目, 自动进行线程扩容.
// 可以会创建很多个线程, 系统负担大, 不好
// ExecutorService service = Executors.newCachedThreadPool();
// 2. 固定创建10个线程的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10000; i++) {
int id = i;
// 往线程池里添加任务
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello " + id + ", " + Thread.currentThread().getName());
}
});
}
}
}
4. 自己实现线程池
查看代码
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyThreadPool {
// 阻塞队列
private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
// 初始化 创建固定线程的线程池 (FixedThreadPool)
public MyThreadPool(int n) {
for (int i = 0;i < n;i++) {
Thread t = new Thread( () -> {
try {
while (true) {
Runnable runnable = queue.take();
runnable.run();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
t.start();
}
}
// 把任务添加到线程池中
public void submit(Runnable runnable) throws InterruptedException {
queue.put(runnable);
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThreadPool threadPool = new MyThreadPool(10);
for (int i = 0;i < 10000;i++) {
// 往线程池里添加任务
int id = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello " + id + ", " + Thread.currentThread().getName());
}
});
}
}
}
关于核心线程, 最大线程数的调整
查看代码
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
// 写一个比较简单的线程池.
class MyThreadPool {
private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
private int maxPoolSize = 0;
private List<Thread> threadList = new ArrayList<>();
// 初始化线程池 (FixedThreadPool)
public MyThreadPool(int corePoolSize, int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
// 创建若干个线程
for (int i = 0; i < corePoolSize; i++) {
Thread t = new Thread(() -> {
try {
while (true) {
Runnable runnable = queue.take();
runnable.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t.start();
threadList.add(t);
}
}
// 把任务添加到线程池中
void submit(Runnable runnable) throws InterruptedException {
// 此处进行判定, 判定说当前任务队列的元素个数, 是否比较长.
// 如果队列元素比较长, 说明已有的线程, 不太能处理过来了. 创建新的线程即可.
// 如果队列不是很长, 没必要创建新的线程.
queue.put(runnable);
// 这里的 阈值 都是咱们拍脑门想的.
while (queue.size() >= 500 && threadList.size() < maxPoolSize) {
// 创建新的线程即可
Thread t = new Thread(() -> {
try {
while (true) {
Runnable task = queue.take();
task.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t.start();
threadList.add(t);
}
}
}
class Demo35 {
public static void main(String[] args) throws InterruptedException {
MyThreadPool threadPool = new MyThreadPool(10, 20);
for (int i = 0; i < 10000; i++) {
int id = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello " + id + ", " + Thread.currentThread().getName());
}
});
}
}
}
5. 定时器
库函数实现:
查看代码
import java.util.Timer;
import java.util.TimerTask;
class Demo36 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello 3000");
}
}, 3000);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello 2000");
}
}, 2000);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello 1000");
}
}, 1000);
}
}
自己实现:
查看代码
import java.util.Comparator;
import java.util.PriorityQueue;
class MyTimerTask implements Comparator<MyTimerTask>,Comparable<MyTimerTask> {
private Runnable runnable;
private long time;
public MyTimerTask(Runnable runnable, long delay) {
this.runnable = runnable;
this.time += System.currentTimeMillis() + delay;
}
public void run() {
this.runnable.run();
}
public long getTime() {
return this.time;
}
@Override
public int compare(MyTimerTask o1, MyTimerTask o2) {
return (int) (o1.time - o2.time);
}
@Override
public int compareTo(MyTimerTask o) {
return (int) (this.time - o.time);
}
}
class MyTimer {
// 得是小跟堆, 谁总时间小,谁优先级高
private PriorityQueue<MyTimerTask> heap = new PriorityQueue<>();
private Object locker = new Object();
// 添加任务进小根堆
public void schedule(Runnable runnable,long delay) {
synchronized (locker) {
MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
heap.offer(myTimerTask);
locker.notify();
}
}
public MyTimer() {
Thread t = new Thread( () -> {
try {
synchronized (locker) {
while (true) {
if (heap.isEmpty()) {
locker.wait();
}
MyTimerTask top = heap.peek();
long curTime = System.currentTimeMillis();
if (top.getTime() <= curTime) {
// 任务可以执行了
top.run();
heap.poll();
}else {
// 任务制定时间 - 当前时间 = 需要等待的时间
locker.wait(top.getTime() - curTime);
}
}
}
}catch (InterruptedException e) {
e.printStackTrace();
}
});
t.start();
}
}
class Test {
public static void main(String[] args) {
MyTimer timer = new MyTimer();
timer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("hello 3000");
}
}, 3000);
timer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("hello 2000");
}
}, 2000);
timer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("hello 1000");
}
}, 1000);
}
}