Thread和ThreadPoolExecutor

Thread

  • 调用Thread.start() 会创建新线程,在新线程里面调用run方法
  • 调用Thread.run()跟调用普通函数没有区别,相当于在当前线程执行任务
  • Thread().start() -> Thread.run() -> Runnable.run();
public class Thread implements Runnable {

    //Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    //It is never legal to start a thread more than once.
    //In particular, a thread may not be restarted once it has completed execution
    public synchronized void start() {
        start0();
    }

    private native void start0();

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
}

ExecutorSerivce的submit与execute的区别

submit会返回Future,execute返回void

  • Method submit extends base method Executor.execute by creating and returning a Future that can be used to cancel execution and/or wait for completion.
  • There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked or not, is then part of the task’s return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will rethrow this exception, wrapped in an ExecutionException.

ThreadPoolExecutor线程池实现原理

Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:

  • If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
  • If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
  • If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.

ThreadPoolExecutor源码

public class ThreadPoolExecutor extends AbstractExecutorService {

    private final BlockingQueue<Runnable> workQueue;

    private final HashSet<Worker> workers = new HashSet<Worker>();
    
    public void execute(Runnable command) {
        if (workerCountOf(c) < corePoolSize) {
            addWorker(command, true);
        } else if (isRunning(c) && workQueue.offer(command)) {
            ...
        } else if (!addWorker(command, false)) {
            reject(command);
        }
    }

    private boolean addWorker(Runnable firstTask, boolean core) {
        int wc = workerCountOf(c);
        if (wc >= CAPACITY || wc >= (core? corePoolSize : maxmumPoolSize))
            return false;

        Worker w = new Worker(firstTask);
        Thread t = w.thread;

        workders.add(w);
        t.start();
    }
    
    private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
        
        final Thread thread;
        
        Runnable firstTask;

        Worker(Runnable firstTask) {
           this.firstTask = firstTask;
           this.thread = getThreadFactory().newThread(this);
        }

        public void run() {
            runWorker(this);
        }
    }

    final void runWorker(Worker w) {
        Runnable task = w.firstTask;
        while (task != null || (task = getTask()) != null) {
            task.run();
        }
    }

    private Runnable getTask() {

        for(;;) {
        {
            int wc = workerCountOf(c);
            boolean timed = wc > corePoolSize;

            Runnable r = timed? worQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take();
            if ( r != null)
                return r;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值