学静思语
Published on 2025-03-21 / 8 Visits
0
0

多线程

多线程

  • 多线程是什么
  • 多线程是指从软硬件上实现的多条执行流程的技术(多条线程由CPU负责调度执行)。

一、多线程的创建方式

1. 方式一:继承Thread类

package com.leon.thread;

/**
 * ClassName:Create_Thread_Method_01
 * Package:com.leon.thread
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class Create_Thread_Method_01 {

    public static void main(String[] args){
        // 创建Thread对象
        Thread thread = new MyThread();
        // 调用start方法
        // 这里不能直接调用run方法,因为那样的话就是一个单线程了
        // 调用start方法向cpu注册线程
        thread.start();
        //thread.run();

        for (int i = 0; i < 10; i++) {

            System.out.println("main: " + i);

        }


    }


}

// 继承Thread类,成为线程类
class MyThread extends Thread{

    // 重写run方法,run方法中是线程要做的事。
    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("MyThread: " + i);
        }

    }
}

1.1 实现方式

  • 创建一个MyThread类继承java.lang.Thread类,重写run方法
  • 创建MyThread线程类对象
  • 调用Thread类中start方法启动线程(启动后还是执行run方法)

1.2 优缺点

  • 优点:编码简单
  • 缺点:线程已经继承Thread,无法继承其他类,不利于功能的扩展。(因为Java是单继承机制)

1.3注意事项

  • 启动线程必须调用start方法,不是调用run方法
  • 直接调用run方法会当成普通方法执行,此时相当于还是单线程执行
  • 只有调用start方法才是启动一个新的线程执行
  • 不要把主线任务放在启动子线程之前
  • 这样主线程一直是先跑完的相当于是一个单线程的效果

2.方式二:实现Runnable接口

package com.leon.thread.createthread;

/**
 * ClassName:Create_Thread_Methos_02
 * Package:com.leon.thread.createthread
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class Create_Thread_Method_02 {

    public static void main(String[] args) {
        // 创建MyRunnable对象
        Runnable runnable = new MyRunnable();
        // 创建Thread对象,将线程任务对象放入到Thread类的有参构造器中
        Thread thread = new Thread(runnable);
        // 启动线程
        thread.start();

        // 简化方式一
        new Thread(runnable).start();

        // 简化方式二
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                System.out.println("MyRunnable: " + i);
            }
        }).start();

        for (int i = 0; i < 10; i++) {

            System.out.println("main: " + i);

        }

    }

}
// 创建线程任务类,实现Runnable接口
class MyRunnable implements Runnable{

    // 实现run方法
    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("MyRunnable: " + i);
        }

    }
}

2.1 实现方式

  • 定义一个线程任务类MyRunnable实现Runnable接口,重写run接口

  • 创建MyRunnable的对象

  • 把MyRunnable任务对象交给Thread处理。

    | Thread类提供的有参构造器 | 说明 |
    | —————————— | —————————- |
    | public Thread(Runnable target) | 封装Runnable对象成为线程对象 |

  • 调用线程对象的start()方法启动线程

2.2 优缺点

  • 优点
  • 任务类只是实现了Runnable接口,可以继续继承其他类、实现其他接口,扩展性更强
  • 缺点
  • 需要多一个Runnable对象

3.方式三:实现Callable接口,可以通过泛型指定返回数据的类型

  • 之前两种线程创建方式都存在的一个问题
  • 假如线程执行完毕后有一些数据需要返回,他们重写的run方法均都不能直接返回结果
package com.leon.thread.createthread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * ClassName:Create_Thread_method_03
 * Package:com.leon.thread.createthread
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class Create_Thread_method_03 {

    public static void main(String[] args) {

        // 创建MyCallable对象
        Callable<String> callable = new MyCallable();

        // 将对象封装成FutureTask线程任务对象
        FutureTask<String> futureTask = new FutureTask<>(callable);

        // 在将任务线程对现象放入到Thread类中,调用start方法
        new Thread(futureTask).start();

        for (int i = 0; i < 10; i++) {

            System.out.println("main: " + i);

        }

        try {
            String string = futureTask.get();
            System.out.println(string);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }



    }

}

// 创建一个对象实现Callable接口,并指定返回值类
class MyCallable implements Callable<String> {

    private int sum;

    // 重写call方法
    @Override
    public String call() throws Exception {



        for (int i = 0; i < 10; i++) {
            System.out.println("MyRunnable: " + i);
            sum += i;
        }



        return "最后的结果为: "+ sum;
    }
}

3.1 创建方式

  • 创建任务对象
  • 定义一个类实现Callable接口,重写call方法,封装要处理的事情以及要返回的数据。
  • 把Callable类型的对象封装成FutureTask(线程任务对象)
  • 把线程任务对象交给Thread对象
  • 调用Thread对象的start方法启动线程
  • 线程执行完毕之后,通过FutureTask对象的get方法获取线程任务执行的结果

3.2 优缺点

  • 优点
  • 线程任务类只是实现接口,可以继续继承和实现其他接口,扩展性强,可以在线程执行完毕后去获取线程执行的结果
  • 缺点
  • 编码复杂一点

3.3注意事项

  • 使用FutureTask对象获取,线程任务执行后的结果,如果线程没有执行完,会等线程执行完之后再获取结果

  • FutureTask的API

    | FutureTask提供的构造器 | 说明 |
    | —————————————– | ———————————- |
    | public FutureTask(Callable callable){} | 把Callable对象封装成FutureTask对象 |

    | FutureTask提供的方法 | 说明 |
    | ———————————————————— | —————————— |
    | public V get() throws InterruptedException, ExecutionException{} | 获取线程执行call方法返回的结果 |

二、线程常用方法

1. Thread常用方法

  • run()
  • 线程的任务方法
  • start()
  • 启动线程
  • getName()
  • 获取当前线程的名称
  • setName(String name)
  • 为线程设置名称
  • currentThread()
  • 获取当前执行的线程对象
  • sleep(long time)
  • 让当前执行的线程休眠多少毫秒后继续执行
  • join()
  • 让调用当前这个方法的线程先执行完

2. Thread常见构造器

  • public Thread(String name)
  • 可以为当前线程指定名称
  • public Thread(Runnable target)
  • 封装Runnable对象成为线程对象
  • public Thread(Runnable target, String name)
  • 封装Runnable对象成为线程对象,并指定名称
package com.leon.thread.threadapi;

/**
 * ClassName:ThreadApiTest
 * Package:com.leon.thread.threadapi
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class ThreadApiTest {

    public static void main(String[] args) {

        Thread thread = new MyThreadApi("运行1号");
        // 设置线程名称
        //thread.setName("运行1号");
        // 启动线程
        thread.start();

        //new MyThreadApi("运行2号").start();

        new Thread(new MyThreadApi2(),"运行2号").start();



        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+ "-mina-: " + i);
            if(i == 2){
                try {
                    // 让当前调用这个方法的线程执行完
                    thread.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }


}

class MyThreadApi extends Thread{

    public MyThreadApi(String name){
        super(name);
    }

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            // Thread.currentThread() 获取当前线程
            // Thread.currentThread().getName()获取当前线程的名称
            System.out.println(Thread.currentThread().getName()+ " - MyThreadApi: " + i);
            //try {
            //    // 让当前线程睡眠1秒
            //    Thread.sleep(1000);
            //
            //} catch (InterruptedException e) {
            //    throw new RuntimeException(e);
            //}
        }
    }
}

class MyThreadApi2 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            // Thread.currentThread() 获取当前线程
            // Thread.currentThread().getName()获取当前线程的名称
            System.out.println(Thread.currentThread().getName()+ " - MyThreadApi2: " + i);

        }

    }
}

三、线程安全问题

1. 什么是线程安全问题

  • 多个线程同时操作同一个共享资源的时候,可能会出现业务安全问题。

2. 线程安全问题出现的原因

  • 存在多个线程在同时执行
  • 同时访问一个共享资源
  • 存在修改该共享资源

3. 案例演示

  • 创建Account类

    package com.leon.thread.threadsafety;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
    
  • ClassName:Account

  • Package:com.leon.thread.threadsafety

  • Description:
    *

  • @Author: leon

  • @Version: 1.0
    */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Account {

    private Integer cardId ;

    private double money;

    public void get(double money){

      if(this.money >= money ){
    
          System.out.println(Thread.currentThread().getName()+ " 吐出金额为: " + money);
    
          this.money  -= money ;
    
          System.out.println(Thread.currentThread().getName()+" 余额为"+ this.money);
    
      }else {
          System.out.println("抱歉余额不足!!");
      }
    

    }

    }

  • 创建线程模拟环境

    package com.leon.thread.threadsafety;
    
    /**
    
  • ClassName:ThreadSafetyTest

  • Package:com.leon.thread.threadsafety

  • Description:
    *

  • @Author: leon

  • @Version: 1.0
    */
    public class ThreadSafetyTest {

    public static void main(String[] args) {

      // 创建账号
      Account account = new Account();
      // 设置账号余额
      account.setMoney(10000);
      // 创建小明线程
      Thread thread = new MyThreadSafety("小明",account);
      // 创建小红线程
      Thread thread2 = new MyThreadSafety("小红",account);
    
      // 同时启动线程
      thread.start();
      thread2.start();
    

    }

    }

    class MyThreadSafety extends Thread{

    private Account account ;

    public MyThreadSafety(String name, Account account) {

      super(name);
      this.account = account;
    

    }

    @Override
    public void run() {

      account.get(10000);
    

    }
    }

四、线程同步

  • 解决线程安全问题的方案

1. 线程同步的思想

  • 让多个线程实现先后依次访问共享资源,这样解决了安全问题。

2. 线程同步的常见方案

  • 加锁:每次只允许一个线程加锁,加锁后才能进入访问,访问完毕后自动解锁,然后其他线程才能再加锁进来

3. 加锁

3.1 同步代码块

  • 核心使用:synchronized

  • 作用:把访问共享资源的核心代码给上锁,以此保证线程安全。

  • 原理:每次只允许一个线程加锁后进入,执行完毕后自动解锁,其他线程才可以进来执行

3.1.1 同步锁注意事项
  • 对于当前同时执行的线程来说,同步锁必须是同一把(同一个对象),否则会出现bug
3.1.2 同步锁问题
  • 锁对象随便选择一个唯一的对象好不好呢?
  • 不好,会影响其他无关线程的执行
  • 锁对象的使用规范
  • 建议使用共享资源作为锁对象,对于实例方法建议使用this作为锁对象
  • 对于静态方法建议使用字节码(类名.class)对象作为锁对象
    public void get(double money){
        // 试用版同步锁,来解决线程安全问题
        synchronized(this){

            if(this.money >= money ){

                System.out.println(Thread.currentThread().getName()+ " 吐出金额为: " + money);

                this.money  -= money ;

                System.out.println(Thread.currentThread().getName()+" 余额为"+ this.money);

            }else {
                System.out.println("抱歉余额不足!!");
            }
        }




    }

3.2 同步方法

  • 作用:把访问共享资源的核心方法给上锁,以保证线程安全。
  • 原理:每次只能一个线程进入,执行完毕以后自动解锁,其他现场版 才可以进来执行。
  • 同步方法底层原理
  • 同步方法其实底层也是有隐式锁对象的,只是锁的范围是整个方法代码。
  • 如果方法是实例方法:同步方法默认使用的是this作为锁对象
  • 如果方法是静态方法:同步方法默认使用的是类名.class作为的锁对象
 public synchronized void get(double money){
        // 试用版同步锁,来解决线程安全问题
        //synchronized(this){

            if(this.money >= money ){

                System.out.println(Thread.currentThread().getName()+ " 吐出金额为: " + money);

                this.money  -= money ;

                System.out.println(Thread.currentThread().getName()+" 余额为"+ this.money);

            }else {
                System.out.println("抱歉余额不足!!");
            }
        //}
    }
3.2.1 同步代码块和同步方法哪个更好
  • 范围:同步代码块锁的范围更小,同步方法锁的范围更大
  • 可读性:同步方法方法更好

3.3 Lock锁

  • Lock锁是JDK5开始提供的一个新的锁定操作,通过它可以创建出锁对象进行加锁和解锁,更灵活、更方便、更强大。

  • Lock是接口,不能直接实例化,可以采用它的实现类ReentrantLock来构建Lock锁对象。

    | 构造器 | 说明 |
    | :——————–: | :——————: |
    | public ReentrantLock() | 获得Lock的实现类对象 |

  • Lock的常用方法

    | 方法名称 | 说明 |
    | :———–: | :—-: |
    | void lock() | 获得锁 |
    | void unlock() | 释放锁 |

    package com.leon.thread.threadsafety;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
    
  • ClassName:Account

  • Package:com.leon.thread.threadsafety

  • Description:
    *

  • @Author: leon

  • @Version: 1.0
    */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Account {

    private Integer cardId;

    private double money;

    private Lock lock = new ReentrantLock();

    public /synchronized /void get(double money) {

      // 试用版同步锁,来解决线程安全问题
      //synchronized(this){
    
      lock.lock();
    
      try {
          if (this.money >= money) {
    
              System.out.println(Thread.currentThread().getName() + " 吐出金额为: " + money);
    
              this.money -= money;
    
              System.out.println(Thread.currentThread().getName() + " 余额为" + this.money);
    
          } else {
              System.out.println("抱歉余额不足!!");
          }
      } catch (Exception e) {
          throw new RuntimeException(e);
      } finally {
          lock.unlock();
      }
      //}
    

    }

    }

五、线程通信

1. 什么是线程通信

  • 当多个线程共同操作共享的资源时,线程间通过某种方式相告知自己的状态,以相互协调,并避免无效的资源争夺。

2. 线程通信的常见模型(生产者与消费者模型)

  • 生产者线程负责生产数据
  • 消费者线程负责消费生产者生产的数据
  • 注意:生产者生产完数据应该等待自己,通知消费者消费;消费者消费完数据也应该等待自己,再通知生产者生产

3.Object类的等待方法和唤醒方法

| 方法名称 | 说明 |
| :————-: | :———————————————————-: |
| void wait() | 让当前线程等待并释放所占锁,直到另一个线程调用notify()方法或notifyAll()方法 |
| void notify() | 唤醒正在等待的单个线程 |
| void notfyAll() | 唤醒正在等待的所有线程 |

4. 实际案例

package com.leon.thread.threadcommunication;

/**
 * ClassName:Table
 * Package:com.leon.thread.threadcommunication
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class Table {

    private String name;


    public synchronized void consumption() throws Exception {
        if (null != name) {
            // 提示吃完了
            System.out.println(Thread.currentThread().getName() + "吃了" + name);
            // 将包子置空
            name = null;
            // 唤醒其他线程
            this.notifyAll();
            // 等待
            this.wait();


        } else {
            // 唤醒其他线程
            this.notifyAll();
            // 等待
            this.wait();


        }
    }

    public synchronized void production() throws Exception {

        if (null == name) {
            // 生产包子
            name = Thread.currentThread().getName() + "生产的包子";
            // 提示生产完了
            System.out.println(Thread.currentThread().getName() + "生产了包子");
            // 唤醒其他线程
            this.notifyAll();
            // 等待
            this.wait();


        } else {
            // 唤醒其他线程
            this.notifyAll();
            // 等待
            this.wait();

        }
    }


}




package com.leon.thread.threadcommunication;

/**
 * ClassName:ThreadCommunicationTest
 * Package:com.leon.thread.threadcommunication
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class ThreadCommunicationTest {

    public static void main(String[] args) {

        Table table = new Table();

        new MyThread("小明",table).start();
        new MyThread("小红",table).start();

        new MyThread2("大肚婆",table).start();
        new MyThread2("小李子",table).start();
        new MyThread2("厨子",table).start();

    }

}

class MyThread extends Thread{

    private Table table;

    public MyThread(String name,Table table){
        super(name);
        this.table = table;
    }

    @Override
    public void run() {
        while (true){

            try {
                Thread.sleep(1000);

                table.consumption();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}

class MyThread2 extends Thread{

    private  Table table;

    public MyThread2(String name,Table table){
        super(name);
        this.table = table;
    }

    @Override
    public void run() {

        while (true){

            try {
                Thread.sleep(1000);

                table.production();

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }


    }
}

六、线程池

1. 什么是线程池

  • 线程池就是一个可以复用线程的技术

2. 不使用线程池的问题

  • 用户每发起一个请求,后台就需要创建一个新线程来处理,下次新任务来了肯定又要创建新线程处理的,而创建新线程的开销是很大的,并且请求过多时,肯定会产生大量的线程出来,这样会严重影响系统的性能。

3.线程池的工作原理

4. 谁代表了线程池?

  • JDK5.0起提供了代表线程池的接口:ExecutorService

5. 如何得到线程池对象?

  • 方式一
  • 使用ExecutorService的实现类ThreadPoolExecutor自创建一个线程池对象
  • 方式二
  • 使用Executors(线程池的工具类)调用方法返回不同特点的线程池对象

6. ThreadPoolExecutor构造器

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) 
  • 参数一:int corePoolSize :指定线程池的核心线程的数量
  • 参数二:int maximumPoolSize:指定线程池的最大线程数量
  • 参数三:long keepAliveTime:指定临时线程的存活时间
  • 参数四:TimeUnit unit:指定临时线程存活的时间单位(秒、分、时、天)
  • 参数五:BlockingQueue< Runnable > workQueue:指定线程池的任务队列
  • 参数六:ThreadFactory threadFactory:指定线程池的线程工厂
  • 参数七:RejectedExecutionHandler handler:指定线程池的任务拒绝策略(线程都在忙,任务队列也满了的时候,新任务来了该怎么处理)

7. 注意事项

  • 临时线程什么时候创建?
  • 新任务提交时发现核心线程都在忙,任务队列也满了,并且还可以创建临时线程,此时才会创建临时线程。
  • 什么时候会开始拒绝新任务?
  • 核心线程和临时线程都在忙,任务队列也满了,新任务过来的时候才会开始拒绝任务。

8. ExecutorService的常用方法

| 方法名称 | 说明 |
| ————————————– | ———————————————————— |
| void execute(Runnable command) | 执行Runnable任务 |
| Future< T > submit(Callable< T > task) | 执行Callable任务,返回未来任务对象,用于获取线程返回的结果 |
| void shutdown() | 等全部任务执行完毕后,再关闭线程池 |
| List< Runnable > shutdownNow() | 立即关闭线程池,停止正在执行的任务,并返回队列中未执行的任务 |

9. 新任务拒绝策略

| 策略 | 详解 |
| ————————————– | ———————————————————- |
| ThreadPoolExecutor.AbortPolicy | 丢弃任务并抛出RejectedExecutionException异常。是默认的策略 |
| ThreadPoolExecutor.DiscardPolicy | 丢弃任务,但是不抛出异常这是不推荐的做法 |
| ThreadPoolExecutor.DiscardOldestPolicy | 抛弃队列中等待最久的任务,然后把当前任务加入队列中 |
| ThreadPoolExecutor.CallerRunsPolicy | 由主线程负责调用任务的run()方法从而绕过线程池直接执行 |

10. Runnable接口

package com.leon.thread.executor;

/**
 * ClassName:MyRunnoable
 * Package:com.leon.thread.executor
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class MyRunnable  implements Runnable{


    @Override
    public void run() {
        for (int i = 0 ; i < 10 ; i++){
            System.out.println(Thread.currentThread().getName() + "----->" + i);
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }
}

package com.leon.thread.executor;

import java.util.List;
import java.util.concurrent.*;

/**
 * ClassName:ThreadPoolExecutorTest
 * Package:com.leon.thread.executor
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class ThreadPoolExecutorTest {


    public static void main(String[] args) {

        //ThreadPoolExecutor
        /*
        * public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)

        *   静态内部类的创建方式为:new 外部类.静态内部类()
        *   内部类创建方式为:new 外部类.new 内部类()
        *
        * */
        ExecutorService executor = new ThreadPoolExecutor(3,5,10,
                TimeUnit.SECONDS,new ArrayBlockingQueue<>(3),Executors.defaultThreadFactory()
                ,new ThreadPoolExecutor.AbortPolicy());

        Runnable runnable = new MyRunnable();

        // 执行Runnable任务
        executor.execute(runnable);
        // 执行Runnable任务
        executor.execute(runnable);
        // 执行Runnable任务
        executor.execute(runnable);
        // 复用任务
        executor.execute(runnable);
        executor.execute(runnable);
        executor.execute(runnable);
        // 临时线程
        executor.execute(runnable);
        executor.execute(runnable);
        executor.execute(runnable);
        executor.execute(runnable);
        executor.execute(runnable);
        executor.execute(runnable);

        // 等所有任务执行完之后再关闭线程池
        //executor.shutdown();

        // 立即关闭线程池,不管是否还有任务
        //executor.shutdownNow();

    }

}

11. Callable接口

package com.leon.thread.executor;

import java.util.concurrent.Callable;

/**
 * ClassName:MyCallable
 * Package:com.leon.thread.executor
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class MyCallable implements Callable<String> {

    private int sum;

    @Override
    public String call() throws Exception {

        for (int i = 0; i < 10; i++) {

            System.out.println(Thread.currentThread().getName()+"----------->"  + i);

            sum += i;

        }


        return "最终结果为 ===>" + sum;
    }
}


package com.leon.thread.executor;

import java.util.concurrent.*;

/**
 * ClassName:ThreadPoolExecutorTest
 * Package:com.leon.thread.executor
 * Description:
 *
 * @Author: leon
 * @Version: 1.0
 */
public class ThreadPoolExecutorTest2 {


    public static void main(String[] args) {

        //ThreadPoolExecutor
        /*
        * public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)

        *   静态内部类的创建方式为:new 外部类.静态内部类()
        *   内部类创建方式为:new 外部类.new 内部类()
        *
        * */
        ExecutorService executor = new ThreadPoolExecutor(3, 5, 10,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.AbortPolicy());
        // 提交任务
        Future<String> submit = executor.submit(new MyCallable());
        Future<String> submit2 = executor.submit(new MyCallable());
        Future<String> submit3 = executor.submit(new MyCallable());
        // 服用线程
        executor.submit(new MyCallable());
        executor.submit(new MyCallable());
        executor.submit(new MyCallable());
        // 临时线程
        executor.submit(new MyCallable());


        try {
            String s1 = submit.get();
            String s2 = submit2.get();
            String s3 = submit3.get();
            System.out.println(s1);
            System.out.println(s2);
            System.out.println(s3);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}

12. Executors

  • 是一个线程池的工具类,提供了很多静态方法用于返回不同特点的线程池对象

| 方法名称 | 说明 |
| ———————————————————— | ———————————————————— |
| public static ExecutorService newFixedThreadPool(int nThreads) | 创建固定线程数量的线程池,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程替代它 |
| public static ExecutorService newSingleThreadExecutor() | 创建只有一个线程的线程池对象,如果该线程出现异常而结束,那么线程池会补充一个新线程 |
| public static ExecutorService newCachedThreadPool() | 线程数量随着任务增加而增加,如果线程任务执行完毕且空闲了60s则会被回收掉 |
| public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) | 创建一个线程池,可以实现在给定的延迟后运行任务,或者定期执行任务 |

13. Executors使用可能存在的陷阱

  • 大型并发系统环境中使用Executor如果不注意可能会出现系统风险。
  • 阿里巴巴Java卡法手册
  • 【强制】线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
    • FixedThreadPool和SingleThreadPool:
    • 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。
    • CachedThreadPool和ScheduledThreadPool:
    • 允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。

七、并发并行

1. 进程

  • 正在运行的程序(软件)就是一个独立的进程。
  • 线程是属于进程的,一个进程中可以同时运行多个线程。
  • 进程中的多线程其实是并发和并行执行的。

2. 并发的含义

  • 进程中的线程是由CPU负责调度执行的,但CPU能同时处理线程的数量有限,为了保证全部线程都能往前执行,CPU会轮询为系统的每个线程服务,由于CPU切换的速度很快,给我们的感觉这些线程在同时执行,这就是并发。

3. 并行的理解

  • 在同一时刻,同时有多个线程在被CPU调度执行

4. 简单说多线程是怎么执行的?

  • 并发:CPU分时论询的执行线程
  • 并行:同一个时刻同时在执行

八、线程的生命周期

1. 线程的生命周期

  • 也就是线程从创建到销毁的过程,经历的各种状态及状态转换
  • 理解线程这些状态有利于提升并发编程的理解能力

2. Java线程的状态

  • Java总共定义了6种状态
  • 6种状态都定义在Thread类的内部枚举类中。
public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called {@code Object.wait()}
         * on an object is waiting for another thread to call
         * {@code Object.notify()} or {@code Object.notifyAll()} on
         * that object. A thread that has called {@code Thread.join()}
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

3. 多线程6种状态的相互转换图


Comment