1. 程式人生 > >springboot專案執行緒使用

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}; } } }

執行緒非同步執行結果: