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;
        }
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ThreadPoolExecutorthreadFactory参数是用来创建新线程的工厂。它是一个接口类型,通常需要实现ThreadFactory接口。 通过提供自定义的ThreadFactory,可以对线程的创建过程进行定制化。例如,可以设置线程的名称、优先级、是否为守护线程等。 以下是一个示例代码,展示了如何使用threadFactory参数创建一个ThreadPoolExecutor: ```java import java.util.concurrent.*; public class ThreadPoolExample { public static void main(String[] args) { // 创建自定义的ThreadFactory ThreadFactory threadFactory = new CustomThreadFactory(); // 创建ThreadPoolExecutor并指定threadFactory ThreadPoolExecutor executor = new ThreadPoolExecutor( 5, 10, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), threadFactory); // 执行任务 for (int i = 0; i < 10; i++) { executor.execute(new Task()); } // 关闭线程池 executor.shutdown(); } static class CustomThreadFactory implements ThreadFactory { private int counter = 0; @Override public Thread newThread(Runnable r) { counter++; String threadName = "CustomThread-" + counter; return new Thread(r, threadName); } } static class Task implements Runnable { @Override public void run() { System.out.println("Task executed by " + Thread.currentThread().getName()); } } } ``` 在上述代码中,我们通过实现ThreadFactory接口创建了一个自定义的线程工厂CustomThreadFactory。在newThread方法中,我们为每个新线程设置了一个名称,并返回一个新的Thread对象。 然后,我们使用指定的threadFactory创建了一个ThreadPoolExecutor,并提交了一些任务。执行这些任务时,会由创建的线程池中的线程来执行。 注意:ThreadPoolExecutorthreadFactory参数是可选的。如果不指定threadFactory,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值