1 多线程基本内容

1.1 进程 & 线程 的区别

进程:操作系统进行资源分配的基本单位
线程:不同的执行路径

1.2 线程调度的概念

计算机通常只有一个CPU,在任意时刻只能执行一条机器指令,每个线程只有获得CPU的使用权才能执行指令。所谓多线程的并发运行,其实是指从宏观上看,各个线程轮流获得CPU的使用权,分别执行各自的任务。在运行池中,会有多个处于就绪状态的线程在等待CPU,JAVA虚拟机的一项任务就是负责线程的调度,线程调度是指按照特定机制为多个线程分配CPU的使用权。

1.3 线程数怎么设置?设置依据?

image.png
W/C 通过Profiler工具计算

2 创建线程的5种方式

2.1 继承Thread类

  1. package s8_thread.p1;
  2. /**
  3. * 多线程的创建,方式一:继承于Thread类
  4. * 1. 创建一个继承于Thread类的子类
  5. * 2. 重写Thread类的run() --> 将此线程执行的操作声明在run()中
  6. * 3. 创建Thread类的子类的对象
  7. * 4. 通过此对象调用start()
  8. *
  9. * 例子:遍历100以内的所有的偶数
  10. *
  11. * @author shkstart
  12. * @create 2019-02-13 上午 11:46
  13. */
  14. //1. 创建一个继承于Thread类的子类
  15. class MyThread extends Thread {
  16. //2. 重写Thread类的run()
  17. @Override
  18. public void run() {
  19. for (int i = 0; i < 100; i++) {
  20. if(i % 2 == 0){
  21. System.out.println(Thread.currentThread().getName() + ":" + i);
  22. }
  23. }
  24. }
  25. }
  26. public class ThreadTest {
  27. public static void main(String[] args) {
  28. //3. 创建Thread类的子类的对象
  29. MyThread t1 = new MyThread();
  30. //4.通过此对象调用start():①启动当前线程 ② 调用当前线程的run()
  31. t1.start();
  32. MyThread t2 = new MyThread();
  33. t2.start();
  34. //如下操作仍然是在main线程中执行的。
  35. for (int i = 0; i < 100; i++) {
  36. if(i % 2 == 0){
  37. System.out.println(Thread.currentThread().getName() + ":" + i + "***********main()************");
  38. }
  39. }
  40. }
  41. }

2.2 实现Runnable接口

implements Runnable + Thread()

  1. package s8_thread.p1;
  2. /**
  3. * 创建多线程的方式二:实现Runnable接口
  4. * 1. 创建一个实现了Runnable接口的类
  5. * 2. 实现类去实现Runnable中的抽象方法:run()
  6. * 3. 创建实现类的对象
  7. * 4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
  8. * 5. 通过Thread类的对象调用start()
  9. * <p>
  10. * <p>
  11. * 比较创建线程的两种方式。
  12. * 开发中:优先选择:实现Runnable接口的方式
  13. * 原因:1. 实现的方式没有类的单继承性的局限性
  14. * 2. 实现的方式更适合来处理多个线程有共享数据的情况。
  15. * <p>
  16. * 联系:public class Thread implements Runnable
  17. * 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
  18. *
  19. * @author shkstart
  20. * @create 2019-02-13 下午 4:34
  21. */
  22. //1. 创建一个实现了Runnable接口的类
  23. class MThread implements Runnable{
  24. //2. 实现类去实现Runnable中的抽象方法:run()
  25. @Override
  26. public void run() {
  27. for (int i = 0; i < 100; i++) {
  28. if(i % 2 == 0){
  29. System.out.println(Thread.currentThread().getName() + ":" + i);
  30. }
  31. }
  32. }
  33. }
  34. public class ThreadTest1 {
  35. public static void main(String[] args) {
  36. //3. 创建实现类的对象
  37. MThread mThread = new MThread();
  38. //4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
  39. Thread t1 = new Thread(mThread);
  40. t1.setName("线程1");
  41. //5. 通过Thread类的对象调用start():① 启动线程 ②调用当前线程的run()-->调用了Runnable类型的target的run()
  42. t1.start();
  43. //再启动一个线程,遍历100以内的偶数
  44. Thread t2 = new Thread(mThread);
  45. t2.setName("线程2");
  46. t2.start();
  47. }
  48. }

2.3 Lambda表达式写法

2.4 实现Callable接口

implements Callable + FutureTask -> Thread()

  1. package s8_thread.p3;
  2. import java.util.concurrent.Callable;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.FutureTask;
  5. /**
  6. * 创建线程的方式三:实现Callable接口。 --- JDK 5.0新增
  7. *
  8. *
  9. * 如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
  10. * 1. call()可以有返回值的。
  11. * 2. call()可以抛出异常,被外面的操作捕获,获取异常的信息
  12. * 3. Callable是支持泛型的
  13. *
  14. * @author shkstart
  15. * @create 2019-02-15 下午 6:01
  16. */
  17. //1.创建一个实现Callable的实现类
  18. class NumThread implements Callable{
  19. //2.实现call方法,将此线程需要执行的操作声明在call()中
  20. @Override
  21. public Object call() throws Exception {
  22. int sum = 0;
  23. for (int i = 1; i <= 100; i++) {
  24. if(i % 2 == 0){
  25. System.out.println(i);
  26. sum += i;
  27. }
  28. }
  29. return sum;
  30. }
  31. }
  32. public class ThreadNew {
  33. public static void main(String[] args) {
  34. //3.创建Callable接口实现类的对象
  35. NumThread numThread = new NumThread();
  36. //4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
  37. FutureTask futureTask = new FutureTask(numThread);
  38. //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
  39. new Thread(futureTask).start();
  40. try {
  41. //6.获取Callable中call方法的返回值
  42. //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
  43. Object sum = futureTask.get();
  44. System.out.println("总和为:" + sum);
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. } catch (ExecutionException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }

2.5 线程池

Executors.newFixedThreadPool(10);

  1. package s8_thread.p3;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. /**
  6. * 创建线程的方式四:使用线程池
  7. *
  8. * 好处:
  9. * 1.提高响应速度(减少了创建新线程的时间)
  10. * 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
  11. * 3.便于线程管理
  12. * corePoolSize:核心池的大小
  13. * maximumPoolSize:最大线程数
  14. * keepAliveTime:线程没有任务时最多保持多长时间后会终止
  15. *
  16. *
  17. * 面试题:创建多线程有几种方式?四种!
  18. * @author shkstart
  19. * @create 2019-02-15 下午 6:30
  20. */
  21. class NumberThread implements Runnable{
  22. @Override
  23. public void run() {
  24. for(int i = 0;i <= 100;i++){
  25. if(i % 2 == 0){
  26. System.out.println(Thread.currentThread().getName() + ": " + i);
  27. }
  28. }
  29. }
  30. }
  31. class NumberThread1 implements Runnable{
  32. @Override
  33. public void run() {
  34. for(int i = 0;i <= 100;i++){
  35. if(i % 2 != 0){
  36. System.out.println(Thread.currentThread().getName() + ": " + i);
  37. }
  38. }
  39. }
  40. }
  41. public class ThreadPool {
  42. public static void main(String[] args) {
  43. //1. 提供指定线程数量的线程池
  44. ExecutorService service = Executors.newFixedThreadPool(10);
  45. ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
  46. //设置线程池的属性
  47. // System.out.println(service.getClass());
  48. // service1.setCorePoolSize(15);
  49. // service1.setKeepAliveTime();
  50. //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
  51. service.execute(new NumberThread());//适合适用于Runnable
  52. service.execute(new NumberThread1());//适合适用于Runnable
  53. // service.submit(Callable callable);//适合使用于Callable
  54. //3.关闭连接池
  55. service.shutdown();
  56. }
  57. }

3 线程间的交互

3.1 线程方法

sleep();线程休息期间,其他线程可以进来
yield();短暂休息一下
join();在t1上运行t2.join(),即等t2运行结束了,再运行t1

3.2 线程的6种状态

  1. NEW:线程刚刚创建,还没有启动
    2. RUNNABLE:可运行状态,由线程调度器可以安排执行
    3. WAITING:等待被唤醒
    4. TIMED WAITING:隔一段时间后自动唤醒
    5. BLOCKED:被阻塞,正在等待锁
    6. TERMINATED:线程结束
    image.png

3.3 线程“打断”

① 线程”打断”的3种方法

  1. MyThread t = new MyThread()
  2. public void interrupt()
  3. // t.interrupt()
  4. // 打断t线程(设置t线程某个标记位f=true,并不是打断线程的运行)
  5. public boolean isInterrupted()
  6. // t.isInterrupted()
  7. // 查询打断标志位是否被设置(是不是曾经被打断过)
  8. public static boolean interrupted()
  9. // Thread.isInterrupted()
  10. // 查看“当前”进程是否被打断,如果被打断,恢复标志位

两个例子:
image.png
image.png
interrupted()是静态方法,只会对当前线程进行查询&重置

② interrupted与sleep,wait
image.png
image.png
调用sleep、wait,可以对这样的线程调用interrupt()设置标志位,被中断后会抛InterruptedException异常(这一步会把标志位复位),然后需要对“异常”进行正确的处理

③ interrupted与synchronized、lock
interrupt()无法干扰锁竞争过程:synchronized、lock(需要用lockInterruptibly())

④ interrupted与lockInterruptibly
如果想打断正在竞争锁的线程,用ReentrantLock的lock.lockInterruptibly()
image.png
image.png
lock.lockInterruptibly()相当于盯着当前线程是否有人设置标志位,有的话则抛出异常

3.4 线程的结束

image.png

  1. stop()方法

    已弃用。方法比较粗暴,stop方法调用的时候会打开全部的锁,容易产生数据不一致的问题

  2. suspend() & resume() - 暂停&继续

已弃用,原因和stop一样(容易产生死锁、数据不一致的问题)

  1. volatile

比较难控制具体的结束时间
无法在循环里使用sleep和wait
image.png

  1. interrupt (更加优雅)

image.png