并发编程(一):初识多线程及线程通信

缺乏、安全感 2023-10-10 10:07 169阅读 0赞

一,线程三种启动方式

  1. 1Thread方式
  2. package com.gupao.concurrent;
  3. /**
  4. * @author pj_zhang
  5. * @create 2019-09-24 21:06
  6. **/
  7. public class StartThread extends Thread {
  8. @Override
  9. public void run() {
  10. System.out.println("Thread方式执行线程。。。");
  11. }
  12. public static void main(String[] args) {
  13. // 普通方式执行
  14. new StartThread().start();
  15. // lamdo表达式执行
  16. new Thread(() -> {
  17. System.out.println("lamdo: Thread方式执行线程。。。");
  18. }).start();
  19. }
  20. }
  21. 2Runnable方式
  22. package com.gupao.concurrent;
  23. /**
  24. * @author pj_zhang
  25. * @create 2019-09-24 21:12
  26. **/
  27. public class StartRunnable implements Runnable {
  28. @Override
  29. public void run() {
  30. System.out.println("Runnable方式执行线程。。。");
  31. }
  32. public static void main(String[] args) {
  33. new Thread(new StartRunnable()).start();
  34. }
  35. }
  36. 3Callable方式 -- 带返回值
  37. \* 不同于ThreadRunnable方式,Callable执行线程后可以返回线程执行结果
  38. \* 通过返回结果Funtureget()结果集时,会阻塞直到结果返回
  39. package com.gupao.concurrent;
  40. import java.util.concurrent.*;
  41. /**
  42. * @author pj_zhang
  43. * @create 2019-09-24 21:13
  44. **/
  45. public class StartCallable implements Callable {
  46. @Override
  47. public Object call() throws Exception {
  48. TimeUnit.SECONDS.sleep(3);
  49. return "Callable方式执行线程";
  50. }
  51. public static void main(String[] args) throws ExecutionException, InterruptedException {
  52. ExecutorService service = new ThreadPoolExecutor(
  53. 20, 20, 0L,
  54. TimeUnit.SECONDS, new LinkedBlockingQueue<>());
  55. Long startTime;
  56. Long endTime;
  57. System.out.println("开始执行时间:" + (startTime = System.currentTimeMillis()));
  58. Future<?> future = service.submit(new StartCallable());
  59. String result = (String) future.get();
  60. System.out.println("执行结束时间" + (endTime = System.currentTimeMillis()));
  61. System.out.println(result + ", cast: " + (endTime - startTime));
  62. }
  63. }

二,线程声明周期(六种线程状态)

  1. 1,线程状态
  2. \* NEW(线程初始化)
  3. \* RUNNABLE(线程运行)
  4. aReady(就绪)
  5. bRunning(运行)
  6. cNEW -(start())-> RUNNABLE
  7. dReady -线程调度-> Running
  8. eRunning -(yield()/线程调度)-> Ready
  9. \* TERMINATED(线程销毁)
  10. \* BLOKED(线程阻塞状态,锁抢占)
  11. asynchorized加锁
  12. \* WAITING(线程等待)
  13. await()
  14. bjoin()
  15. cLockSupport.park()
  16. \* TIME\_WAITING(线程限时等待)
  17. await(Long)
  18. bsleep(Long)
  19. 2,线程状态转换演示\_代码
  20. package com.gupao.concurrent;
  21. import java.util.concurrent.locks.Lock;
  22. import java.util.concurrent.locks.ReentrantLock;
  23. /**
  24. * @author pj_zhang
  25. * @create 2019-09-24 21:42
  26. **/
  27. public class ThreadStatusTest {
  28. public static void main(String[] args) {
  29. // 运行时线程
  30. new Thread(() -> {
  31. for (;;) {}
  32. }, "THREAD_RUNNING").start();
  33. // 等待线程
  34. new Thread(() -> {
  35. try {
  36. Object object = new Object();
  37. synchronized (object) {
  38. object.wait();
  39. }
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. }, "THREAD_WAITING").start();
  44. // 定时等待线程
  45. new Thread(() -> {
  46. try {
  47. Object object = new Object();
  48. synchronized (object) {
  49. object.wait(60 * 60 * 1000);
  50. }
  51. } catch (InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. }, "TIME_WAITING_THREAD").start();
  55. Lock lock = new ReentrantLock();
  56. // 未阻塞线程
  57. new Thread(() -> {
  58. synchronized (lock) {
  59. for (; ; ) {}
  60. }
  61. }, "NOT_BLOCKING_THREAD").start();
  62. // 阻塞线程
  63. new Thread(() -> {
  64. try {
  65. Thread.sleep(1000);
  66. synchronized (lock) {
  67. for (;;) {}
  68. }
  69. } catch (InterruptedException e) {
  70. e.printStackTrace();
  71. }
  72. }, "BLOCKING_THREAD").start();
  73. }
  74. }
  75. 3,线程状态转换演示\_状态查看
  76. \* 通过 jps 命令查看正在执行的线程PID

2019092422281056.png

  1. \* 通过 jstack pid 命令,查看正在执行的所有线程及其状态

20190924222836870.png

  1. \* 从中可以依次看到定义中的几种线程状态

20190924222914515.png

20190924222925414.png

20190924222943513.png

20190924223000419.png

2019092422301841.png

三,线程中断

  1. 1,线程中断:thread.interrupt()
  2. 2,判断线程是否中断:Thread.currentThread().isInterrupted()
  3. 3,线程中断代码演示;如下代码,interrupt()提供了一种可控的方式对线程进行中断,执行中断操作后,被中断线程可以根据当前业务运行情况在对应安全点对线程中断操作进行响应
  4. package com.gupao.concurrent;
  5. /**
  6. * @author pj_zhang
  7. * @create 2019-09-24 22:33
  8. **/
  9. public class ThreadInterruptTest {
  10. private static int i = 0;
  11. public static void main(String[] args) throws InterruptedException {
  12. Thread thread = new Thread(() -> {
  13. // 线程初始化后,默认中断状态为false
  14. // 等其他线程对当前线程执行中断操作后,线程状态变为true
  15. for (; !Thread.currentThread().isInterrupted(); ) {
  16. i++;
  17. }
  18. System.out.println(i);
  19. // 打印当前线程中断状态
  20. System.out.println(Thread.currentThread().isInterrupted());
  21. });
  22. thread.start();
  23. // 主线程睡眠一秒后,对线程进行中断操作
  24. Thread.sleep(1000);
  25. thread.interrupt();
  26. }
  27. }

20190924224052189.png

  1. 4,线程等待中的线程中断演示,会抛出 InterruptedException 异常,(异常后会对线程中断状态进行复位,在下一部分解释)
  2. package com.gupao.concurrent;
  3. /**
  4. * @author pj_zhang
  5. * @create 2019-09-24 22:33
  6. **/
  7. public class ThreadWaitingInterruptTest {
  8. private static int i = 0;
  9. public static void main(String[] args) throws InterruptedException {
  10. Thread thread = new Thread(() -> {
  11. try {
  12. // 线程等待十秒,主线程1秒后中断,则必定触发中断异常
  13. Thread.sleep(10000);
  14. } catch (InterruptedException e) {
  15. // 异常后, 线程会自动复位
  16. // 主线程调用interrupt后,线程中断状态从false -> true
  17. // 由于触发异常,则对线程中断重新赋值为初始状态false
  18. System.out.println("响应线程中断。。。,线程中断状态:"
  19. + Thread.currentThread().isInterrupted());
  20. }
  21. });
  22. thread.start();
  23. // 主线程睡眠一秒后,对线程进行中断操作
  24. Thread.sleep(1000);
  25. thread.interrupt();
  26. }
  27. }

20190924224708652.png

四,线程复位

  1. 1,线程中断是给执行一个中断信号,告诉执行线程已经进行了线程中断操作,具体后续操作由执行线程进行后续处理,执行线程在接收到线程中断信号后,可以对线程中断状态进行复位;
  2. 2,线程复位两种方式
  3. aAPI复位:Thread.interrupted()
  4. package com.gupao.concurrent;
  5. /**
  6. * @author pj_zhang
  7. * @create 2019-09-24 22:33
  8. **/
  9. public class ThreadInterruptTest {
  10. private static int i = 0;
  11. public static void main(String[] args) throws InterruptedException {
  12. Thread thread = new Thread(() -> {
  13. // 线程初始化后,默认中断状态为false
  14. // 等其他线程对当前线程执行中断操作后,线程状态变为true
  15. for (; !Thread.currentThread().isInterrupted(); ) {
  16. i++;
  17. }
  18. System.out.println(i);
  19. // 线程复位前中断状态
  20. System.out.println("before: " + Thread.currentThread().isInterrupted());
  21. // 线程复位
  22. Thread.interrupted();
  23. // 线程复位后中断状态
  24. System.out.println("after:" + Thread.currentThread().isInterrupted());
  25. });
  26. thread.start();
  27. // 主线程睡眠一秒后,对线程进行中断操作
  28. Thread.sleep(1000);
  29. thread.interrupt();
  30. }
  31. }

20190924225212598.png

  1. b,异常复位:等待中的线程接收到异常信号后,会抛出 InterruptedException 异常,捕获异常后线程状态已经由 JVM 复位,可继续进行后续处理,异常复位已经在上一部分演示;

五,线程通信

  1. 1,线程等待和线程唤醒:wait()/notify()
  2. package com.gupao.concurrent;
  3. /**
  4. * @author pj_zhang
  5. * @create 2019-09-24 23:04
  6. **/
  7. public class ThreadTelTest extends Thread {
  8. // 定义初始数量
  9. private static int i = 100;
  10. // 定义初始标志位
  11. // 此处模拟两道线程运行,通过简单标志位实现
  12. // 如果确实需要通过某种方式实现线程顺序执行,可以通过分布式锁实现
  13. // 参考之前博文中的zookeeper和redis分布式锁
  14. private static boolean flag = false;
  15. // 定义同步锁对象
  16. private static Object lock = new Object();
  17. public static void main(String[] args) {
  18. // 两道线程同时执行
  19. new Thread(new ThreadTelTest(), "售票员A").start();
  20. new Thread(new ThreadTelTest(), "售票员B").start();
  21. }
  22. @Override
  23. public void run() {
  24. try {
  25. for (;;) {
  26. synchronized (lock) {
  27. if (i > 0) {
  28. // flag为true,说明已经存在线程执行过,
  29. // 当前线程为新线程或者被唤醒线程,且执行过的线程目前处于等待中
  30. if (flag) {
  31. System.out.println(Thread.currentThread().getName() + "卖出第" + i-- + "张票");
  32. // 线程执行完成后,唤醒处于等待中线程
  33. lock.notify();
  34. // 当前线程等待,并释放锁对象,被唤醒的线程会直接抢占锁对象
  35. lock.wait();
  36. } else {
  37. // flag为false,说明当前线程第一次进入,执行完业务代码后,修改flag表示为true
  38. System.out.println(Thread.currentThread().getName() + "卖出第" + i-- + "张票");
  39. flag = true;
  40. // 线程等待,实现两道线程交替执行,因为是第一个进入的线程,不需要唤醒线程
  41. lock.wait();
  42. }
  43. } else {
  44. System.out.println("卖完了");
  45. break;
  46. }
  47. }
  48. }
  49. } catch (InterruptedException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. 2,线程排队:join()
  55. \* 线程排队执行代码演示
  56. package com.gupao.concurrent;
  57. /**
  58. * @author pj_zhang
  59. * @create 2019-09-24 22:52
  60. **/
  61. public class ThreadJoinTest {
  62. public static void main(String[] args) throws InterruptedException {
  63. Thread t1 = new Thread(() -> {
  64. try {
  65. // 通过不规则定时,演示线程随机执行
  66. Thread.sleep(200);
  67. System.out.println("线程一执行结束。。。");
  68. } catch (InterruptedException e) {
  69. e.printStackTrace();
  70. }
  71. });
  72. Thread t2 = new Thread(() -> {
  73. try {
  74. Thread.sleep(20);
  75. System.out.println("线程二执行结束。。。");
  76. } catch (InterruptedException e) {
  77. e.printStackTrace();
  78. }
  79. });
  80. Thread t3 = new Thread(() -> {
  81. System.out.println("线程三执行结束。。。");
  82. });
  83. // 通过 join 方法,保证线程排队执行
  84. t1.start();
  85. t1.join();
  86. t2.start();
  87. t2.join();
  88. t3.start();
  89. t3.join();
  90. }
  91. }
  92. \* join()方法内部;
  93. public final synchronized void join(long millis)
  94. throws InterruptedException {
  95. long base = System.currentTimeMillis();
  96. long now = 0;
  97. if (millis < 0) {
  98. throw new IllegalArgumentException("timeout value is negative");
  99. }
  100. if (millis == 0) {
  101. // 从这一步可以看到,如果当前线程依旧存活,则阻塞主线程
  102. // 通过自旋一直等待直到线程执行结束
  103. while (isAlive()) {
  104. wait(0);
  105. }
  106. } else {
  107. // 这一部分表示限时阻塞
  108. while (isAlive()) {
  109. long delay = millis - now;
  110. if (delay <= 0) {
  111. break;
  112. }
  113. wait(delay);
  114. now = System.currentTimeMillis() - base;
  115. }
  116. }
  117. }
  118. \* 从方法源码看,join()通过对主线程的阻塞实现线程方法的顺序执行,如果在上一步直接start()三道线程,再对线程逐一进行join(),则线程三会瞬间抢占时间片并执行,从而乱序,如图

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTE5NzYzODg_size_16_color_FFFFFF_t_70

发表评论

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

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

相关阅读

    相关 并发线

     一个程序同时执行多个任务。 通常,每一个任务称为一个线程 ( thread ) , 它是线程控制的简称。 可以同时运行一个以上线程的程序称为多线程程序 ( multithre