美文网首页
线程等待

线程等待

作者: 09c72470861c | 来源:发表于2021-03-05 11:12 被阅读0次

自己看的,乱写的,勿喷

线程配置类

package mau5.top.myproject.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadAsyncConfigurer implements AsyncConfigurer {

    private final static Logger log = LoggerFactory.getLogger(ThreadAsyncConfigurer.class);

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        threadPool.setCorePoolSize(3);
        // 设置最大线程数
        threadPool.setMaxPoolSize(8);
        // 线程池所使用的缓冲队列
        threadPool.setQueueCapacity(10);
        // 等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(60);
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }

    /**
     * 异常处理
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }

    /**
     * 自定义异常处理类
     */
    class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            log.error("==========================" + throwable.getMessage() + "=======================", throwable);
            log.error("exception method:" + method.getName());
            for (Object param : obj) {
                log.error("Parameter value - " + param);
            }
        }
    }
}

写一个Callable实现类实现业务

package mau5.top.myproject.business.callable;

import java.util.concurrent.*;

public class TestCallable implements Callable {
    @Override
    public Object call() throws Exception {

        int random = (int) (Math.random() * 10000);
        System.out.println("随机生成数:" + random);
        Thread.sleep(random);
        return random;
    }    
}

调用Callable实现类

package mau5.top.myproject.business.controller;

import mau5.top.myproject.business.callable.TestCallable;
import mau5.top.myproject.business.entity.po.CommodityCategory;
import mau5.top.myproject.business.service.ICommodityCategoryService;
import mau5.top.myproject.common.config.ThreadAsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/cate")
public class CommodityCategoryController {

    @Resource
    private ThreadAsyncConfigurer threadAsyncConfigurer;

    @GetMapping("/testCallable")
    public Object callable(){
        try {
            long currentTimeMillis = System.currentTimeMillis();
            TestCallable callable = new TestCallable();

            // 手动创建线程
            // ExecutorService executor = Executors.newFixedThreadPool(3);
            // 使用线程池
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor)threadAsyncConfigurer.getAsyncExecutor();

            Future<Integer> submit1 = executor.submit(callable);
            Future<Integer> submit2 = executor.submit(callable);
            Future<Integer> submit3 = executor.submit(callable);

            int s = submit1.get() + submit2.get() +submit3.get();

            long currentTimeMillis2 = System.currentTimeMillis();

            System.out.println("总共时间:" + s);
            System.out.println("耗时:" + (currentTimeMillis2 - currentTimeMillis));
            // 非线程池时才用shutdown
            // executor.shutdown();
            
            return  "总共时间:" + s + ",耗时:" + (currentTimeMillis2 - currentTimeMillis);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

相关文章

  • 计数器:CountDownLatch,CountDownLatc

    计数器 CountDownLatch: 一个线程等待多个线程。 CyclicBarrier:多个线程相互等待,等待...

  • C++ 线程类thread

    c++ 线程类 thread 注:join 是线程等待,等待子线程结束后在继续执行;线程等待要用sleep_for...

  • C++同步并发操作

    何时需要线程同步 线程完成前,需要等待另一个线程执行 线程需要等待特定事件发生 线程等待某个条件变为true 线程...

  • Kotlin线程(4)线程管理

    等待线程结束 (join)线程让步 (yield)线程停止 一、等待线程结束   当一个线程调用其它线程(t1)的...

  • 三、线程间协调

    父线程开启、中断、等待子线程结束 阻塞等待获取异步线程的执行结果 等待-通知模型,条件不满足休眠等待 Synchn...

  • 如何估算最大线程数

    线程等待时间所占比例越高,需要越多线程。线程CPU时间所占比例越高,需要越少线程。 最佳线程数目 = (线程等待时...

  • 5、多线程-线程种类

    一、线程种类1、守护线程:是为用户线程服务的,jvm停止不用等待守护线程执行完毕。2、用户线程:jvm等待用户线程...

  • 06 通知等待机制

    等待-通知机制:如果线程要求的条件不满足,则线程阻塞自己,进入等待状态;当线程要求的条件满足后,通知等待的线程重新...

  • Java中的并发工具类

    CountDownLatch等待多线程完成 CountDownLatch允许一个或多个线程等待其他线程完成操作。 ...

  • Java并发-25.并发工具类-CountDownLatch

    等待多线程完成的CountDownLatch CountDownLatch允许一个或者多个线程等待其他线程完成操作...

网友评论

      本文标题:线程等待

      本文链接:https://www.haomeiwen.com/subject/tpdrqltx.html