加入收藏 | 设为首页 | 会员中心 | 我要投稿 武汉站长网 (https://www.027zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 移动互联 > 评测 > 正文

3年工作经验,工作中还不会使用多线程?阿里P6:别慌,我都总结好了

发布时间:2019-07-18 21:56:10 所属栏目:评测 来源:Jay_huaxiao
导读:副标题#e# 掌握线程池是后端程序员的基本要求,相信大家求职面试过程中,几乎都会被问到有关于线程池的问题。我在网上搜集了几道经典的线程池面试题,并以此为切入点,谈谈我对线程池的理解。如果有哪里理解不正确,非常希望大家指出,接下来大家一起分析学

虽然没有结果输出,但是没有抛出异常,所以我们无法感知任务出现了异常,所以需要添加try/catch。 如下图:

3年工作经验,工作中还不会使用多线程?阿里P6:别慌,我都总结好了

OK,线程的异常处理,我们可以直接try...catch捕获。线程池exec.submit(runnable)的执行流程

通过debug上面有异常的submit方法(建议大家也去debug看一下,图上的每个方法内部是我打断点的地方),处理有异常submit方法的主要执行流程图:

3年工作经验,工作中还不会使用多线程?阿里P6:别慌,我都总结好了  
  1. //构造feature对象 
  2. /** 
  3. * @throws RejectedExecutionException {@inheritDoc} 
  4. * @throws NullPointerException {@inheritDoc} 
  5. */ 
  6. public Future<?> submit(Runnable task) { 
  7. if (task == null) throw new NullPointerException(); 
  8. RunnableFuture<Void> ftask = newTaskFor(task, null); 
  9. execute(ftask); 
  10. return ftask; 
  11. protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { 
  12. return new FutureTask<T>(runnable, value); 
  13. public FutureTask(Runnable runnable, V result) { 
  14. this.callable = Executors.callable(runnable, result); 
  15. this.state = NEW; // ensure visibility of callable 
  16. public static <T> Callable<T> callable(Runnable task, T result) { 
  17. if (task == null) 
  18. throw new NullPointerException(); 
  19. return new RunnableAdapter<T>(task, result); 
  20. //线程池执行 
  21. public void execute(Runnable command) { 
  22. if (command == null) 
  23. throw new NullPointerException(); 
  24. int c = ctl.get(); 
  25. if (workerCountOf(c) < corePoolSize) { 
  26. if (addWorker(command, true)) 
  27. return; 
  28. c = ctl.get(); 
  29. if (isRunning(c) && workQueue.offer(command)) { 
  30. int recheck = ctl.get(); 
  31. if (! isRunning(recheck) && remove(command)) 
  32. reject(command); 
  33. else if (workerCountOf(recheck) == 0) 
  34. addWorker(null, false); 
  35. else if (!addWorker(command, false)) 
  36. reject(command); 
  37. //捕获异常 
  38. public void run() { 
  39. if (state != NEW || 
  40. !UNSAFE.compareAndSwapObject(this, runnerOffset, 
  41. null, Thread.currentThread())) 
  42. return; 
  43. try { 
  44. Callable<V> c = callable; 
  45. if (c != null && state == NEW) { 
  46. V result; 
  47. boolean ran; 
  48. try { 
  49. result = c.call(); 
  50. ran = true; 
  51. } catch (Throwable ex) { 
  52. result = null; 
  53. ran = false; 
  54. setException(ex); 
  55. if (ran) 
  56. set(result); 
  57. } finally { 
  58. // runner must be non-null until state is settled to 
  59. // prevent concurrent calls to run() 
  60. runner = null; 
  61. // state must be re-read after nulling runner to prevent 
  62. // leaked interrupts 
  63. int s = state; 
  64. if (s >= INTERRUPTING) 
  65. handlePossibleCancellationInterrupt(s); 
  66. 制代码 

(编辑:武汉站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读