关于java:线程池springboot工程中的异步

36次阅读

共计 2177 个字符,预计需要花费 6 分钟才能阅读完成。

Spring boot 工程中的异步

SpringBoot 工程中默认反对异步操作,然而咱们须要首先在启动类的下面,增加启动异步操作的注解 (@EnableAsync) 形容,代码如下:

@EnableAsync
@SpringBootApplication
public class DbpmsApplication {public static void main(String[] args) {SpringApplication.run(DbpmsApplication.class, args);
 }
 }

如果此时某个业务办法须要执行异步操作,能够应用 @Async 注解对办法进行形容,例如写日志的业务,要害代码如下

@Async// 次注解形容的办法为异步切入点办法
@Override
public void saveLog(SysLog sysLog) {
    try {Thread.sleep(10000);
    } catch (InterruptedException e) {e.printStackTrace();
    }
    System.out.println("findLogs.thread="+Thread.currentThread().getName());
    sysLogDao.insertLog(sysLog);
}

其中,@Async 注解形容的办法,在 spring 中会认为这是一个异步切入点办法,在这个切入点办法执行时,底层会通过告诉办法获取线程池中的线程,通过池中的线程调用切入点办法(底层默认池类 ThreadPoolExecutor 类型)
简略应用 ThreadPoolExecutor 创立线程池

package com.cy;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
public class ThreadPoolExecutorTests {
    // 创立工作队列,存储执行的工作
 static BlockingQueue<Runnable> workQueue=
            new ArrayBlockingQueue<>(1);
    // 构建线程工厂
 static ThreadFactory threadFactory=new ThreadFactory() {
        // 线程前缀
 private String prefix="pool-thread-task-";
        // 定义一个提供自增自减机制的对象
 private AtomicLong atomicLong=new AtomicLong(1);
        @Override
 public Thread newThread(Runnable r) {return new Thread(r, prefix+atomicLong.getAndIncrement());
        }
    };
    public static void main(String[] args) {
        // 初始化一个线程池
 ThreadPoolExecutor tpool=
                new ThreadPoolExecutor(1,
                        2,
                        3,
                        TimeUnit.SECONDS,
                        workQueue,
                        threadFactory,
                        new ThreadPoolExecutor.AbortPolicy());
        tpool.execute(new Runnable() {
            @Override
 public void run() {String task=Thread.currentThread().getName()+"->task01";
                System.out.println(task);
                try {Thread.sleep(3000);
                } catch (InterruptedException e) {e.printStackTrace();
                }
            }
        });
        tpool.execute(new Runnable() {
            @Override
 public void run() {String task=Thread.currentThread().getName()+"->task02";
                System.out.println(task);
                try{Thread.sleep(3000);}catch (Exception e){}}
        });
        tpool.execute(new Runnable() {
            @Override
 public void run() {String task=Thread.currentThread().getName()+"->task03";
                System.out.println(task);
                try{Thread.sleep(3000);}catch (Exception e){}}
        });
        tpool.execute(new Runnable() {
            @Override
 public void run() {String task=Thread.currentThread().getName()+"->task04";
                System.out.println(task);
                try{Thread.sleep(3000);}catch (Exception e){}}
        });
    }
}

后果:

pool-thread-task-1->task01
pool-thread-task-2->task03
pool-thread-task-1->task02// 期待 3 秒呈现

Java 多线程:彻底搞懂线程池

正文完
 0