zoukankan      html  css  js  c++  java
  • springboot项目线程使用

    下面是一个demo:

    public class TestThread {
    
        
        private static int nThreads =Runtime.getRuntime().availableProcessors() * 2 + 1;  //创建的线程数理论最优值是cpu核数的2n+1
        
        private static ExecutorService executors = Executors.newFixedThreadPool(nThreads, new ThreadFactory() {  //创建线程池
            
            private final String threadNamePrefix="thread_name_task_";
            
            private final AtomicInteger count = new AtomicInteger(1);//原子性操作,保证每个线程数值的安全性
            
            
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(Thread.currentThread().getThreadGroup(),r,threadNamePrefix + count.getAndIncrement());
                t.setDaemon(true);
                return t;
            }
        });
        
    
        
            public static void main(String[] args) {
                
                List<Future<String[]>> fList = new ArrayList<>();
                
                
                for (int i = 0; i < 10; i++) {
                    final int nextInt = new Random().nextInt(100);
                    Future<String[]> f  =  executors.submit(new TestTask(nextInt));
                    
                    fList.add(f);
                }
                
                /*for (Future<String[]> future : fList) {
                    try {
                        String [] result = future.get();
                        System.out.println(result[0]  + " , 结果   "  + result[1]);
                    } catch (InterruptedException e) {
                    } catch (ExecutionException e) {
                    }
                }
                
                
                
                System.out.println("main 线程结束 ");
                
            }
            
            
        static class TestTask  implements Callable<String[]> {
            
                private int i ;
                
                public TestTask(int i){
                    this.i = i;
                }
                
                @Override
                public String[] call() throws Exception {
                    String result =  i%2 == 0 ? "S" : "F";
                    // 业务处理逻辑
                    //Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "第" + i + "次任务");
                    return new String[] {Thread.currentThread().getName(),result};
                }
         }
    }

    线程异步执行结果:

  • 相关阅读:
    樊登读书 认知天性
    【笔记】Tapable源码解析图以及webpack怎样实现一个插件plugin
    web前端使用mcg-helper代码生成工具学习笔记
    博客记录
    15ISK 驱动 BIOS等
    蒙特卡洛方法和蒙特卡洛树搜索
    求最大k个数
    求阶乘的位数和后缀0个数
    五分钟看懂一致性哈希算法
    Windows下查看GPU(NVIDIA)使用情况
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/9957325.html
Copyright © 2011-2022 走看看