Skip to content

线程的使用

一、runnable方法的定义

Runnable接口为关联Thread对象的线程提供执行代码。这些代码放在Runnable的run方法当中,这个方法没有返回值但是可能会抛出异常。

二、手动创建线程的方式

  1. 继承Thread类创建线程
public class MyThread extends Thread{//继承Thread类
  public void run(){
  //重写run方法
  }
}
  1. 实现Runnable接口创建线程
public class MyThread2 implements Runnable {//实现Runnable接口
  public void run(){
  //重写run方法
  }
}
  1. 使用Callable和Future创建线程
CallableTest callableTest = new CallableTest() ;
        //因为Callable接口是函数式接口,可以使用Lambda表达式
        FutureTask<Integer> task = new FutureTask<Integer>((Callable<Integer>)()->{
           int i = 0 ;
           for(;i<100;i++){
               System.out.println(Thread.currentThread().getName() + "的循环变量i的值 :" + i);
           }
           return i;
        });
       for(int i=0;i<100;i++){
           System.out.println(Thread.currentThread().getName()+" 的循环变量i : + i");
           if(i==20){
               new Thread(task,"有返回值的线程").start();
           }
       }
       try{
           System.out.println("子线程返回值 : " + task.get());
        }catch (Exception e){
           e.printStackTrace();
        }
  1. 使用线程池例如Executor框架
public static void main(String[] args){
       ExecutorService executorService = Executors.newCachedThreadPool();
//      ExecutorService executorService = Executors.newFixedThreadPool(5);
//      ExecutorService executorService = Executors.newSingleThreadExecutor();
       for (int i = 0; i < 5; i++){
           executorService.execute(new TestRunnable());
           System.out.println("************* a" + i + " *************");
       }
       executorService.shutdown();
   }
}
class TestRunnable implements Runnable{
   public void run(){
       System.out.println(Thread.currentThread().getName() + "线程被调用了。");
   }

二、springboot创建线程池

线程池配置文件

/**
 * @Description 线程池配置文件
 * @Author lcy
 * @Date 2020/4/30 15:20
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor defaultThreadPool(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数量
        threadPoolTaskExecutor.setCorePoolSize(2);
        //最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(5);
        //队列中最大任务数
        threadPoolTaskExecutor.setQueueCapacity(2);
        //线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPool-");
        //当达到最大线程数时如何处理新任务
        //当pool已经达到max size的时候,如何处理新任务,CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后最大存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        //初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}

线程池使用

java
 @Autowired
    private ThreadPoolTaskExecutor threadPool;
    
  public void test(){
   threadPool.execute(() -> {
                System.out.println("已经发送过短信");

        });
  }