JavaEE--多线程 线程池

ThreadPoolExecuter中的参数面试要考

Executors(标准库提供的工厂类)

1.Executors.newCachedThreadPool();

创建一个最普通的线程池,能够根据任务的数目自动进行线程扩容

2.Executors.newFixedThreadPool(n);

创建固定线程数目的线程池

3.Executors.newSingLeThreadExecutor();

创建一个包含单个线程的线程池

4.Executors.newScheduledThreadPool(n); 

创建一个固定线程个数,但是任务延时执行的线程池

public class Demo2 {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();

        for(int i=0; i<10000;i++){
            int id = i;
            service.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello ");
                }
            });
        }
    }
}

如何实现线程池

1)有若干个线程

2)有任务队列(使用Runnable方法)

3)提供submit 

线程池的工作流程

1.执行任务,核心线程数未达到corePoolSize该值,就创建线程。否则塞入任务队列。
2.任务队列满了,就创建线程,但是总线程数不能超过该值maximumPoolSize。
3.如果任务队列满了,线程数达到maximumPoolSize值,则执行失败策略。
4.工作线程则不停的轮询去队列中poll任务,如果poll为空,则工作线程执行结束(回收线程)。
5.如果工作线程数<=核心线程数corePoolSize,则使用take从队列中获取任务(核心线程一直await)。

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
//初始化线程池
    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) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
    void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
}

public class Demo1 {
    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");
                }
            });
        }
    }
}

定时器

定时器就是闹钟效果

import java.util.Comparator;
import java.util.PriorityQueue;

class MyTimerTask implements 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(){
        runnable.run();
    }

    public long getTime(){
        return time;
    }
    @Override
    public int compareTo(MyTimerTask o){
        return(int)(this.time-o.time);
    }
}


class MyTimer{
    private PriorityQueue<MyTimerTask> taskQueue = new PriorityQueue<>();
    private Object locker = new Object();
    public MyTimer(){
        //这个线程负责不停的扫描上述队列队首元素,来确定是否要执行任务
        Thread t = new Thread(()->{
            try{
                while(true){
                    synchronized (locker){
                    if(taskQueue.size()==0){
                        locker.wait();
                    }
                    MyTimerTask task = taskQueue.peek();
                    long curTime = System.currentTimeMillis();
                    if(curTime>=task.getTime()){
                        //时间到了,要执行任务了
                        task.run();
                        taskQueue.poll();
                    }else{
                        locker.wait(task.getTime() - curTime);
                    }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
        MyTimerTask task = new MyTimerTask(runnable,delay);
        taskQueue.offer(task);
        locker.notify();
        }
    }
}

public class Demo3 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        },1000);
    }
}

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值