自定义线程池 和 定时器 之前 让我们先学习使用其基本原理
1.学习使用线程池
//使用线程池
public class demo8 {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
int id=i;
service.submit(()->{
System.out.println("hello "+ id+","+Thread.currentThread().getName());
});
}
}
}
结果如下:

2.学习使用定时器
//学习使用定时器
public class demo10 {
public static void main(String[] args) {
Timer timer =new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello 1000");
}
},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 3000");
}
},1000);
System.out.println("hello main");
}
}
结果如下:

3.自定义线程池
//自定义线程池
class MyThreadPool{
private BlockingQueue<Runnable> queue=null;
public MyThreadPool(int n){
//创建容量为1000的 阻塞队列
queue=new ArrayBlockingQueue<>(1000);
for (int i = 0; i < n; i++) {
//循环创建n个线程
Thread t =new Thread(()->{
try {
//没有任务就等待
//如果有 就取
while (true) {
Runnable task = queue.take();
//执行线程任务
task.run();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
//每次创建一个线程都要启动
t.start();
}
}
public void submit(Runnable task) throws InterruptedException {
queue.put(task);
}
}
4.自定义定时器
//自定义一个定时器
//1.创建一个类 表示任务
//2.使用一个集合类 把这些任务管理起来——小根堆
//3.实现schedule方法 把任务添加到队列里
//4.额外创建一个线程 负责执行队列里的任务
import java.util.PriorityQueue;
class MytimeTask implements Comparable<MytimeTask> {
private Runnable task;
private long time;
public MytimeTask(Runnable task,long time){
this.task=task;
this.time=time;
}
public long getTime() {
return time;
}
public void run() {
task.run();
}
@Override
public int compareTo(MytimeTask o) {
return (int) (this.time- o.time);
// return (int) (o.time -this.time);
}
}
class Mytimer{
//直接使用this 作为锁对象 也可以
private Object locker =new Object();
private PriorityQueue<MytimeTask> queue =new PriorityQueue<>();
public void schedule(Runnable task,long delay_time){
synchronized (locker) {
//以入队列 这个时刻为基准
MytimeTask mytimeTask =new MytimeTask(task,System.currentTimeMillis()+delay_time);
queue.offer(mytimeTask);
locker.notify();
}
}
public Mytimer(){
Thread t =new Thread(()->{
try {
while (true){
synchronized (locker) {
//取队首元素
//使用while更好 可以再次判断是否为空
while (queue.isEmpty()){
//不能空等 按需等待 按需唤醒
//如果使用sleep 时间不好控制
// continue;
locker.wait();
}
MytimeTask task =queue.peek();
if(System.currentTimeMillis()< task.getTime()){
//如果时机未到
// continue;
locker.wait(task.getTime()-System.currentTimeMillis());
}else {
//时间到了 执行任务
task.run();
queue.poll();
}
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
t.start();
}
}

222

被折叠的 条评论
为什么被折叠?



