當(dāng)前位置:首頁 > IT技術(shù) > 編程語言 > 正文

JAVA多線程處理
2021-10-22 16:44:58

針對(duì)io密集型任務(wù),可以采用多線程方式處理,其消耗時(shí)間比單線程大幅度減少。

?

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class ThreadPoolTest {

    public void multiThread(int num) {
        long start = System.currentTimeMillis();
        log.info("start ....");
        //聲明線程池
//        ExecutorService executor = Executors.newFixedThreadPool(8);

        //針對(duì)IO密集型的任務(wù)
        int nThreads = Runtime.getRuntime().availableProcessors() * 2;
        log.info("nThreads:{}",nThreads);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        //該拒絕策略,首先判斷線程池是否關(guān)閉,如果未關(guān)閉,則直接執(zhí)行該線程
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        List<Future<Integer>> futures = new ArrayList<>();
        //批量提交任務(wù)
        for (int i = 0; i < num; i++) {
            int finalI = i;
            futures.add(
                    executor.submit(
                            //線程任務(wù)
                            new Callable<Integer>() {
                                @Override
                                public Integer call() throws Exception {
                                    task(finalI);
                                    return finalI;
                                }
                            }
                    ));
        }
        //獲取執(zhí)行完的結(jié)果
        for (Future<Integer> future : futures) {
            try {
                log.info(String.valueOf(future.get()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        log.info("end cost {} ....", System.currentTimeMillis() - start);
        //關(guān)閉線程池
        executor.shutdown();
    }

    //要執(zhí)行的任務(wù),耗時(shí)200ms
    private void task(int num) {
        try {
            log.info(" task:{} ,currentThread: {} ", num, Thread.currentThread().getName());
            Thread.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //單線程執(zhí)行
    public void singleThread(int num) {
        long start = System.currentTimeMillis();
        log.info("start ....");
        for (int i = 0; i < num; i++) {
            task(i);
        }
        log.info("end cost {} ....", System.currentTimeMillis() - start);
    }

    public static void main(String[] args) {
        ThreadPoolTest concurrentTest = new ThreadPoolTest();
        //單線程耗時(shí)2秒
//        concurrentTest.singleThread(10);
        //多線程耗時(shí)200毫秒
        concurrentTest.multiThread(10);
    }
}

  

本文摘自 :https://www.cnblogs.com/

開通會(huì)員,享受整站包年服務(wù)立即開通 >