淺談線程runnable和callable的使用及區別


線程使用比較廣泛,但實際上一般項目很少用上線程,線程常用於優化復雜的程序執行流程,把一些與業務關系關系不大但是必須要執行的流程使用線程的方式讓子線程去執行,主流程只返回跟業務有關的信息

runnable是無返回值的執行線程;callable是有返回值的執行線程

實現runable接口的實現類通常使用execute來開啟線程池中的線程來執行任務,但是也支持submit來開啟原則上不會報錯,因為實現類返回結果就是void

實現callable接口的實現類只能用submit來開啟線程池中的線程來執行任務

下面是測試代碼:

public class TestThread {

    private static int nThreads = Runtime.getRuntime().availableProcessors() * 2 + 1;

    private static ExecutorService executors = Executors.newFixedThreadPool(nThreads, new ThreadFactory() {

        private final String threadNamePrefix = "si_query_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 TestTaskcb(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("call線程結束");
        
        for (int i = 0; i < 10; i++) {
            final int nextInt = new Random().nextInt(100);
            executors.execute(new TestTaskvoid(nextInt));
        }
        System.out.println("void線程結束");
        
        System.out.println("main 線程結束 ");

    }

    static class TestTaskcb implements Callable<String[]> {

        private int i;

        public TestTaskcb(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 };
        }
    }
    
    static class TestTaskvoid implements Runnable {

        private int i;

        public TestTaskvoid(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "第" + i + "次任務");
        }
    }
}

 

線程執行是隨機執行的,打印結果不可作參考

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM