JavaEE初阶(8)——自定义线程池&&自定义定时器

自定义线程池 和 定时器 之前 让我们先学习使用其基本原理

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();
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值