14-线程和线程池

客官°小女子只卖身不卖艺 2021-08-29 11:16 530阅读 0赞

线程和线程池

    1. 线程
    • 1.1 什么是线程&多线程
    • 1.2 线程实现的方式
    • 1.3 线程的生命周期&状态
    • 1.4 线程执行顺序
    • 1.5 Callable & Future
    • 1.6 总结
    1. 线程池
    • 2.1 线程池是什么
    • 2.2 线程池的好处
    • 2.3 线程池实现原理
      • 2.3.1 源码分析
      • 2.3.2 工作线程
    • 2.4 线程池的使用
      • 2.4.1 线程池的创建
      • 2.4.2 向线程池提交任务
        • 2.4.2.1 excute()
        • 2.4.2.2 submit()

1. 线程

1.1 什么是线程&多线程

  1. **线程**:
  2. 线程是进程的一个实体,是`CPU`调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。线程自己基本不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但是它可与属同一个进程的其他线程共享进程所拥有的全部资源。
  3. **多线程**:
  4. 多线程指在单个程序中可以同时运行多个不同的线程执行不同的任务。
  5. 多线程编程的目的,就是“最大限度地利用`CPU`资源”,当某一线程地处理不需要占用`CPU`而只和`IO`等资源打交道时,让需要占用`CPU`的其他线程有其他机会获得`CPU`资源。

1.2 线程实现的方式

  • 实现 Runnable 接口
  • 继承 Thread 类
  • 实现 Callable 接口

1.3 线程的生命周期&状态

在这里插入图片描述

在这里插入图片描述

1.4 线程执行顺序

  1. /** * @author wangzhao * @date 2019/9/15 19:48 */
  2. public class ThreadSort {
  3. public static void main(String[] args) throws InterruptedException {
  4. Thread thread1 = new Thread(()->{
  5. System.out.println("thread1");
  6. });
  7. Thread thread2 = new Thread(()->{
  8. System.out.println("thread2");
  9. });
  10. Thread thread3 = new Thread(()->{
  11. System.out.println("thread3");
  12. });
  13. thread1.start();
  14. thread1.join();
  15. thread2.start();
  16. thread2.join();
  17. thread3.start();
  18. thread3.join();
  19. }
  20. }
  21. `join`线程的运行顺序:
  22. thread1
  23. thread2
  24. thread3
  25. `thread1.join()`的含义是运行`thread1.join()`所在的线程等待等待 `thread1` 线程终止后才从thread1.join()返回。
  26. 即当前线程(`main`)只有等待调用该方法的线程结束,才能继续向下执行,否则一直被阻塞在`join()`处。

在这里插入图片描述

  1. public final void join() throws InterruptedException {
  2. join(0);
  3. }
  4. public final synchronized void join(long millis)
  5. throws InterruptedException {
  6. long base = System.currentTimeMillis();
  7. long now = 0;
  8. if (millis < 0) {
  9. throw new IllegalArgumentException("timeout value is negative");
  10. }
  11. if (millis == 0) {
  12. while (isAlive()) {
  13. wait(0);
  14. }
  15. } else {
  16. while (isAlive()) {
  17. long delay = millis - now;
  18. if (delay <= 0) {
  19. break;
  20. }
  21. wait(delay);
  22. now = System.currentTimeMillis() - base;
  23. }
  24. }
  25. }
  26. 我们需要知道的是,线程调用wait()方法必须获取锁,所以`join()`方法是被`synchronized`修饰的,`synchronizaed`修饰在方法层面相当于`synchronized(this)``this`就是`thread1`本身的实例。
  27. 为什么`join`阻塞的是主线程,而不是`thread1`对象?
  28. 因为主线程会持有`thread1`这个对象的锁,然后`thread1`对象调用`wait()`方法去阻塞,而这个方法的调用者是在主线程中的。所以造成主线程阻塞。
  29. 为什么`thread1`线程执行完毕就能够唤醒主线程呢?或者说是在什么时候唤醒的?
  30. 通过`wait`方法阻塞的线程,需要通过`notify`或者`notifyall`来唤醒。所以在线程执行完毕以后会有一个唤醒的操作,只是我们不需要关心。
  31. void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
  32. assert(this == JavaThread::current(), "thread consistency check");
  33. ...
  34. // Notify waiters on thread object. This has to be done after exit() is called
  35. // on the thread (if the thread is the last thread in a daemon ThreadGroup the
  36. // group should have the destroyed bit set before waiters are notified).
  37. ensure_join(this);
  38. assert(!this->has_pending_exception(), "ensure_join should have cleared");
  39. ...
  40. 观察一下 `ensure_join(this)`这行代码上的注释,唤醒处于等待的线程对象,这个是在线程终止之后做的清理工作,这个方法的定义代码片段如下:
  41. static void ensure_join(JavaThread* thread) {
  42. // We do not need to grap the Threads_lock, since we are operating on ourself.
  43. Handle threadObj(thread, thread->threadObj());
  44. assert(threadObj.not_null(), "java thread object must exist");
  45. ObjectLocker lock(threadObj, thread);
  46. // Ignore pending exception (ThreadDeath), since we are exiting anyway
  47. thread->clear_pending_exception();
  48. // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
  49. java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
  50. // Clear the native thread instance - this makes isAlive return false and allows the join()
  51. // to complete once we've done the notify_all below
  52. //这里是清除native线程,这个操作会导致isAlive()方法返回false
  53. java_lang_Thread::set_thread(threadObj(), NULL);
  54. lock.notify_all(thread);//注意这里
  55. // Ignore pending exception (ThreadDeath), since we are exiting anyway
  56. thread->clear_pending_exception();
  57. }
  58. `ensure_join`方法中,调用 `lock.notify_all(thread)`; 唤醒所有等待`thread`锁的线程,意味着调用了`join`方法被阻塞的主线程会被唤醒;
  59. `Thread.join`其实底层是通过`wait/notifyall`来实现线程的通信达到线程阻塞的目的;当线程执行结束以后,会触发两个事情,第一个是设置`native`线程对象为`null`、第二个是通过`notifyall`方法,让等待在`thread1`对象锁上的线程被唤醒。

1.5 Callable & Future

  1. public class CallableTest implements Callable<String> {
  2. @Override
  3. public String call() throws Exception {
  4. return "hello world";
  5. }
  6. public static void main(String[] args) throws ExecutionException, InterruptedException {
  7. FutureTask<String> task = new FutureTask<String>(new CallableTest());
  8. new Thread(task).start();
  9. System.out.println(task.get());
  10. }
  11. }
  12. hello world
  13. 为什么调用`get()`方法会被阻塞?
  14. public FutureTask(Callable<V> callable) {
  15. if (callable == null)
  16. throw new NullPointerException();
  17. this.callable = callable;
  18. this.state = NEW; // ensure visibility of callable
  19. }
  20. public void run() {
  21. if (state != NEW ||
  22. !UNSAFE.compareAndSwapObject(this, runnerOffset,
  23. null, Thread.currentThread()))
  24. return;
  25. try {
  26. Callable<V> c = callable;
  27. if (c != null && state == NEW) {
  28. V result;
  29. boolean ran;
  30. try {
  31. result = c.call();
  32. ran = true;
  33. } catch (Throwable ex) {
  34. result = null;
  35. ran = false;
  36. setException(ex);
  37. }
  38. if (ran)
  39. set(result);
  40. }
  41. } finally {
  42. // runner must be non-null until state is settled to
  43. // prevent concurrent calls to run()
  44. runner = null;
  45. // state must be re-read after nulling runner to prevent
  46. // leaked interrupts
  47. int s = state;
  48. if (s >= INTERRUPTING)
  49. handlePossibleCancellationInterrupt(s);
  50. }
  51. }
  52. public V get() throws InterruptedException, ExecutionException {
  53. int s = state;
  54. if (s <= COMPLETING)
  55. s = awaitDone(false, 0L);
  56. return
  57. report(s);
  58. }
  59. private int awaitDone(boolean timed, long nanos)
  60. throws InterruptedException {
  61. final long deadline = timed ? System.nanoTime() + nanos : 0L;
  62. WaitNode q = null;
  63. boolean queued = false;
  64. for (;;) {
  65. if (Thread.interrupted()) {
  66. removeWaiter(q);
  67. throw new InterruptedException();
  68. }
  69. int s = state;
  70. if (s > COMPLETING) {
  71. if (q != null)
  72. q.thread = null;
  73. return s;
  74. }
  75. else if (s == COMPLETING) // cannot time out yet
  76. Thread.yield();
  77. else if (q == null)
  78. q = new WaitNode();
  79. else if (!queued)
  80. queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
  81. q.next = waiters, q);
  82. else if (timed) {
  83. nanos = deadline - System.nanoTime();
  84. if (nanos <= 0L) {
  85. removeWaiter(q);
  86. return state;
  87. }
  88. LockSupport.parkNanos(this, nanos);
  89. }
  90. else
  91. LockSupport.park(this);
  92. }
  93. }
  94. 通过`state`来判断当前任务是否执行完,如果没有执行完则阻塞。

1.6 总结

  1. **实现Runnable接口相比继承Thread类有如下优势**:
  2. 1)可以避免由于Java的单继承特性而带来的局限
  3. 2)增强程序的健壮性,代码能够被多个线程共享,代码与数据是独立的
  4. 3)线程池只能放入实现`Runnable``Callable`类线程,不能直接放入继承`Thread`的类
  5. **实现Runnable接口和实现Callable接口的区别**:
  6. 1`Runnable`是自从`Java1.1`就有了,而`Callable``1.5`之后才加上去的
  7. 2)实现`Callable`接口的任务线程能返回执行结果,而实现`Runnable`接口的任务线程不能返回结果
  8. 3`Callable`接口的`call()`方法允许抛出异常,而`Runnable`接口的`run()`方法的异常只能在内部消化,不能向上抛
  9. 4)加上线程池允许,`Runnable`使用`ExecutorService``execute()`方法,`Callable`使用`submit()`方法
  10. 注意:`Callable`接口支持返回指向结果,此时需要调用`FutureTask.get()`方法实现,此方法会阻塞主线程直到获取返回结果,当不调用此方法时,主线程不会阻塞。

2. 线程池

2.1 线程池是什么

  1. 线程池是拥有若干已经创建好的线程的缓冲池,调用者可以直接通过线程池获取已经创建好的线程执行任务。

2.2 线程池的好处

  1. 降低资源消耗:重复利用已创建的线程执行新的任务
  2. 提高响应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行
  3. 提高线程的可管理性:由线程池统一分配、调优和监控线程

2.3 线程池实现原理

  1. 当提交一个新任务到线程池时,线程池的处理流程如下:

在这里插入图片描述

  1. `ThreadPoolExecutor`执行 `execute()`方法的示意图:

在这里插入图片描述
ThreadPoolExecutor执行execute方法分下面4种情况:

  1. 1)如果当前运行的线程少于 `corePoolSize` ,则创建新线程来执行任务(注意,执行这一步骤需要获取全局锁)
  2. 2)如果运行的线程等于或多于`corePoolSize` ,则将任务加入`BlockingQueue`
  3. 3)如果无法将任务加入`BlockingQueue`(队列已满),则创建新的线程来处理任务(注意,执行这一步骤需要获取全局锁)
  4. 4)如果新创建线程将使当前运行的线程超出 `maximumPoolsize`,任务将被拒绝,并调用`RejectedExecutionHandler.rejectedExecution()`方法。
  5. 为什么要将线程池分为maximumPool corePool,一个pool不行吗?
  6. 是为了在执行`execute()` 方法 ,尽可能地避免获取全局锁。在`ThreadPoolExecuto`r完成预热之后(当前运行地线程数大于等于`corePoolSize` ),几乎所有的 `execute()`方法调用都是执行步骤2 ,而 步骤2不需要获得锁。
  7. 同时,也可以减少线程被创建的数量。

2.3.1 源码分析

在这里插入图片描述

  1. 成员变量 `ctl` 是一个 `Integer` 的原子变量,用来记录线程池状态和线程池中线程个数。
  2. 假设 `Integer` 类型是 `32`位二进制表示,则其中高 `3` 位用来表示线程池状态,后面 `29` 位用来记录线程池线程个数。
  3. // 默认是 RUNNING 状态,线程个数为0
  4. private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
  5. // 线程个数掩码位数,并不是所有平台的 int 类型都是32位,即具体平台下Integer的二进制位数-3后的剩余位数所
  6. // 表示的数才是线程个数
  7. private static final int COUNT_BITS = Integer.SIZE - 3;
  8. // 线程最大个数(低29位)00011111111111111111111111111111
  9. private static final int CAPACITY = (1 << COUNT_BITS) - 1;
  10. // 线程池状态:
  11. // (高三位) 11100000000000000000000000000000
  12. private static final int RUNNING = -1 << COUNT_BITS;
  13. // (高三位) 00000000000000000000000000000000
  14. private static final int SHUTDOWN = 0 << COUNT_BITS;
  15. // (高三位) 00100000000000000000000000000000
  16. private static final int STOP = 1 << COUNT_BITS;
  17. // (高三位) 01000000000000000000000000000000
  18. private static final int TIDYING = 2 << COUNT_BITS;
  19. // (高三位) 01100000000000000000000000000000
  20. private static final int TERMINATED = 3 << COUNT_BITS;
  21. // 获取高3位(运行状态)
  22. private static int runStateOf(int c){
  23. return c & ~CAPACITY;
  24. }
  25. // 获取低29位(线程个数)
  26. private static int workerCountOf(int c){
  27. return c & CAPACITY;
  28. }
  29. // 计算 ctl 新值(线程状态与线程个数)
  30. private static int ctlOf(int rs,int wc){
  31. return rs | wc;
  32. }
  33. 线程池状态含义如下:
  • RUNNING:接受新任务并且处理阻塞队列里的任务
  • SHUTDOWN:拒绝新任务但是处理阻塞队列里的队伍
  • STOP:拒绝新任务并且抛弃阻塞队列里的任务,同时会中断正在处理的任务
  • TIDYING:所有任务都执行完(包含阻塞队列里面的任务)后当前线程池活动线程数为0,将要调用
    terminated 方法。
  • TERMINSTED:终止状态,terminated方法调用完成以后的状态。

    public void execute(Runnable command) {

    1. if (command == null)
    2. throw new NullPointerException();
    3. int c = ctl.get();
    4. // 1、如果线程数小于核心线程数,则创建线程并执行当前任务
    5. if (workerCountOf(c) < corePoolSize) {
    6. if (addWorker(command, true))
    7. return;
    8. c = ctl.get();
    9. }
    10. // 2、如果线程数大于等于基本线程数或线程创建失败,将当前任务放到工作队列中
    11. if (isRunning(c) && workQueue.offer(command)) {
    12. int recheck = ctl.get();
    13. if (! isRunning(recheck) && remove(command))
    14. reject(command);
    15. else if (workerCountOf(recheck) == 0)
    16. addWorker(null, false);
    17. }
    18. // 3、尝试开启新线程,扩容至maxPoolSize
    19. else if (!addWorker(command, false))
    20. // 4、如果失败,则执行响应的策略
    21. reject(command);
    22. }

2.3.2 工作线程

  1. 线程池创建线程时,会将线程封装成工作线程`Worker``Worker`在执行完任务后,还会循环获取工作队列的任务来执行。

在这里插入图片描述

  1. private final class Worker extends AbstractQueuedSynchronizer implements Runnable{
  2. private static final long serialVersionUID = 6138294804551838833L;
  3. final Thread thread;
  4. Runnable firstTask;
  5. Worker(Runnable firstTask) {
  6. setState(-1); // inhibit interrupts until runWorker
  7. this.firstTask = firstTask;
  8. this.thread = getThreadFactory().newThread(this);
  9. }
  10. /** Delegates main run loop to outer runWorker */
  11. public void run() {
  12. runWorker(this);
  13. }
  14. }
  15. final void runWorker(Worker w) {
  16. Thread wt = Thread.currentThread();
  17. Runnable task = w.firstTask;
  18. w.firstTask = null;
  19. w.unlock(); // allow interrupts
  20. boolean completedAbruptly = true;
  21. try {
  22. while (task != null || (task = getTask()) != null) {
  23. w.lock();
  24. if ((runStateAtLeast(ctl.get(), STOP) ||
  25. (Thread.interrupted() &&
  26. runStateAtLeast(ctl.get(), STOP))) &&
  27. !wt.isInterrupted())
  28. wt.interrupt();
  29. try {
  30. beforeExecute(wt, task);
  31. Throwable thrown = null;
  32. try {
  33. task.run();
  34. } catch (RuntimeException x) {
  35. thrown = x; throw x;
  36. } catch (Error x) {
  37. thrown = x; throw x;
  38. } catch (Throwable x) {
  39. thrown = x; throw new Error(x);
  40. } finally {
  41. afterExecute(task, thrown);
  42. }
  43. } finally {
  44. task = null;
  45. w.completedTasks++;
  46. w.unlock();
  47. }
  48. }
  49. completedAbruptly = false;
  50. } finally {
  51. processWorkerExit(w, completedAbruptly);
  52. }
  53. }
  54. `ThreadPoolExecutor`中线程执行任务的示意图:

在这里插入图片描述
线程池中的线程执行任务分两种情况:

  1. 1)在 `execute()` 方法中创建一个线程时,会让这个线程执行当前任务
  2. 2)这个线程执行完上图中`1`的任务后,会反复从 `BlockingQueue` 获取任务来执行。

2.4 线程池的使用

2.4.1 线程池的创建

  1. new ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. ThreadFactory threadFactory,
  7. RejectedExecutionHandler handler)
  8. 1`corePoolSize`(线程池的基本大小):当提交一个任务到线程池,线程池会创建一个线程来执行任务,即使其他空闲的基本线程能够执行新任务也会创建线程,需要等到需要执行的任务数大于线程池基本大小时就不再创建。
  9. `prestartCoreThread()` , 线程池提前创建并启动所有的基本线程。
  10. 2`maximumPoolSize`(线程池最大数量):线程池允许创建的最大线程数。如果队列满了,并且已创建的线程池小于最大线程数,则线程会再创建新的线程执行任务。如果使用了无界的队列这个参数没有效果。
  11. 3`workQueue`(任务队列):用于保证等待执行的任务的阻塞队列。
  12. 有如下几个可以选择的阻塞队列:
  13. `ArrayBlockingQueue`:基于数组结构的有界阻塞队列。此队列按FIFO原则对元素进行排序。
  14. `LinkedBlockingQueue`:基于链表结构的有界阻塞队列。此队列按FIFO排序元素,吞吐量通常高于ArrayBlockingQueue **静态工厂方法 `Executors.newFixedThreadPool()`使用了这个队列**
  15. `SynchronousQueue`:一个不存储元素的阻塞队列。每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态。吞吐量通常高于`LinkedBlockingQueue`。**静态工厂方法 `Executors.newCachedThreadPool()`使用了这个队列**
  16. `PriorityBlockingQueu`e:一个具有优先级的无限阻塞队列。
  17. 4`ThreadFactory`:用于设置创建线程的工厂,可以通过线程工厂可以对创建的线程做相关设置。
  18. 5`RejectedExecutionHandler`(饱和策略):当队列和线程池都满了,说明线程池处于饱和状态,那么必须采取一种策略处理提交的新任务。这个策略默认情况下是`AbortPolicy`.
  19. 1. `AbortPolicy`:直接抛出异常
  20. 2. `CallerRunsPolicy`:使用调用者所在的线程来运行任务
  21. 3. `DiscardOldestPolicy`:丢弃队列里最老的一个任务,并执行当前任务
  22. 4. `DiscardPolicy`:不处理,丢弃掉
  23. 6`keepAliveTime`(线程活动保持时间):线程池的工作线程空闲后,保持存活的时间。如果任务很多,并且每个任务执行的时间比较短,可以调大时间,提高线程的利用率。
  24. 7`TimeUnit`(线程活动保持时间的单位)

2.4.2 向线程池提交任务

  1. 可以使用两个方法向线程池提交任务,分别为 `execute()` `submit()` 方法:

2.4.2.1 excute()

  1. 该方法用于提交不需要返回值的任务。
  2. public void execute(Runnable command) {
  3. // (1)如果任务为null,抛出NPE异常
  4. if (command == null)
  5. throw new NullPointerException();
  6. // (2)获取当前线程池的状态+线程个数变量的组合值
  7. int c = ctl.get();
  8. // (3)当前线程池中线程个数是否小于 corePoolSize ,小于则开启新线程运行
  9. if (workerCountOf(c) < corePoolSize) {
  10. if (addWorker(command, true))
  11. return;
  12. c = ctl.get();
  13. }
  14. // (4)如果线程池处于 RUNNING 状态,则添加任务到阻塞队列
  15. if (isRunning(c) && workQueue.offer(command)) {
  16. // (4.1)二次检查
  17. int recheck = ctl.get();
  18. // (4.2) 如果当前线程池状态不是 RUNNING 则从队列中删除任务,并执行拒绝策略
  19. if (! isRunning(recheck) && remove(command))
  20. reject(command);
  21. // (4.3)否则如果当前线程为空,则添加一个线程
  22. else if (workerCountOf(recheck) == 0)
  23. addWorker(null, false);
  24. }
  25. // (5)如果队列满,则新增线程,新增失败则执行拒绝策略
  26. else if (!addWorker(command, false))
  27. reject(command);
  28. }
  29. private boolean addWorker(Runnable firstTask, boolean core) {
  30. retry:
  31. for (;;) {
  32. int c = ctl.get();
  33. int rs = runStateOf(c);
  34. // 检查队列是否只在必要时为空
  35. if (rs >= SHUTDOWN &&
  36. ! (rs == SHUTDOWN &&
  37. firstTask == null &&
  38. ! workQueue.isEmpty()))
  39. return false;
  40. // 循环 CAS 增加线程个数
  41. for (;;) {
  42. int wc = workerCountOf(c);
  43. // 如果线程个数超限则返回false
  44. if (wc >= CAPACITY ||
  45. wc >= (core ? corePoolSize : maximumPoolSize))
  46. return false;
  47. // CAS 增加线程个数,同时只有一个线程成功
  48. if (compareAndIncrementWorkerCount(c))
  49. break retry;
  50. // CAS 失败了,则看线程池状态是否变化了,变化则跳到外层循环重新尝试获取线程池
  51. // 状态,否则内存循环重新 CAS
  52. c = ctl.get(); // Re-read ctl
  53. if (runStateOf(c) != rs)
  54. continue retry;
  55. // else CAS failed due to workerCount change; retry inner loop
  56. }
  57. }
  58. // 到这里说明 CAS 成功
  59. boolean workerStarted = false;
  60. boolean workerAdded = false;
  61. Worker w = null;
  62. try {
  63. // 创建一个worker
  64. w = new Worker(firstTask);
  65. final Thread t = w.thread;
  66. if (t != null) {
  67. final ReentrantLock mainLock = this.mainLock;
  68. // 加独占锁,为了实现 worker 同步,因为可能多个线程调用了线程池的 execute 方法
  69. mainLock.lock();
  70. try {
  71. // 重新检查线程池状态,以避免在获取锁前调用了 shutdown 接口
  72. int rs = runStateOf(ctl.get());
  73. if (rs < SHUTDOWN ||
  74. (rs == SHUTDOWN && firstTask == null)) {
  75. if (t.isAlive()) // precheck that t is startable
  76. throw new IllegalThreadStateException();
  77. // 添加任务
  78. workers.add(w);
  79. int s = workers.size();
  80. if (s > largestPoolSize)
  81. largestPoolSize = s;
  82. workerAdded = true;
  83. }
  84. } finally {
  85. mainLock.unlock();
  86. }
  87. // 添加成功后则启动任务
  88. if (workerAdded) {
  89. t.start();
  90. workerStarted = true;
  91. }
  92. }
  93. } finally {
  94. if (! workerStarted)
  95. addWorkerFailed(w);
  96. }
  97. return workerStarted;
  98. }

​ (1)双重循环的目的是通过CAS操作增加线程数

​ (2)把并发安全的任务添加到 worker里面,并且启动任务执行

  1. Worker(Runnable firstTask) {
  2. setState(-1); // 在调用 runworker 之前禁止中断
  3. this.firstTask = firstTask;
  4. this.thread = getThreadFactory().newThread(this);
  5. }
  6. final void runWorker(Worker w) {
  7. Thread wt = Thread.currentThread();
  8. Runnable task = w.firstTask;
  9. w.firstTask = null;
  10. w.unlock(); // 将 state 设置为0,允许中断
  11. boolean completedAbruptly = true;
  12. try {
  13. while (task != null || (task = getTask()) != null) {
  14. w.lock();
  15. if ((runStateAtLeast(ctl.get(), STOP) ||
  16. (Thread.interrupted() &&
  17. runStateAtLeast(ctl.get(), STOP))) &&
  18. !wt.isInterrupted())
  19. wt.interrupt();
  20. try {
  21. // 执行任务前干一些事情
  22. beforeExecute(wt, task);
  23. Throwable thrown = null;
  24. try {
  25. // 执行任务
  26. task.run();
  27. } catch (RuntimeException x) {
  28. thrown = x; throw x;
  29. } catch (Error x) {
  30. thrown = x; throw x;
  31. } catch (Throwable x) {
  32. thrown = x; throw new Error(x);
  33. } finally {
  34. // 执行任务完毕后干一些事情
  35. afterExecute(task, thrown);
  36. }
  37. } finally {
  38. task = null;
  39. // 统计当前 Worker 完成了多少个任务
  40. w.completedTasks++;
  41. w.unlock();
  42. }
  43. }
  44. completedAbruptly = false;
  45. } finally {
  46. // 执行清理工作
  47. processWorkerExit(w, completedAbruptly);
  48. }
  49. }

2.4.2.2 submit()

  1. 用于提交需要返回值的任务。
  2. 线程池会返回一个`future` 类型的对象,通过这个`future`对象可以判断任务是否执行成功,并且可以通过`future` `get()`方法来获取返回值,`get()` 方法会阻塞当前线程直到任务完成。
  3. Future<?> future = threadPool.submit(task);
  4. Object s = future.get();
  5. 可以调用 `shutdown()` `shurdownNow()`方法来关闭线程池。
  6. 原理:遍历线程池中的工作线程,然后逐个调用线程的`interrupt`方法来中断线程,所以无法响应线程中断的任务可能永远无法终止。

  1. `shotdownNow()`将线程池状态设置成`STOP`,然后尝试停止所有的正在执行或暂停任务的线程,并返回等待执行任务的列表。
  2. `shutdown`只是将线程池的状态设置成SHUTDOWN状态,然后中断所有没有正在执行任务的线程。

发表评论

表情:
评论列表 (有 0 条评论,530人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线线

    现在是多核的时代,面向多核编程很重要,因些基于java的并发和多线程编程很重要。 首先要提到的就是线程池,与每次需要创建线程相比,线程池可以降低创建线程的开销,这是因为线程池在

    相关 线线

    软件大师又要给弟子开小灶了,这次是线程和线程池。 软件大师正在闭目修炼, 最小的一名弟子慢慢走了进来。 大师,最近我在学习线程,有很多迷惑的地方。 说来听听,让

    相关 Java线线

    创建线程的方式:继承Thread   、 实现Runnable接口  、实现Callable接口(可以通过Future获取返回结果) 介绍一下通过Callable实现多线程: