java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 线程池exectue与submit的区别

线程池之exectue与submit的区别及说明

作者:Ahuuua

这篇文章主要介绍了线程池之exectue与submit的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1、参数及返回值不同

excute:

submit:

2、异常抛出不同

execute:

import org.junit.Test;
 
import java.util.concurrent.*;
 
public class ThreadPoolDemo {
 
    @Test
    public void test() throws InterruptedException, ExecutionException {
        //创建线程池对象
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.execute(() -> {
            System.out.println("开始");
            int i = 10 / 0;
            System.out.println("结束");
        });
    }
}

输出:

开始
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at ThreadPoolDemo.lambda$test$0(ThreadPoolDemo.java:13)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

submit:

import org.junit.Test;
 
import java.util.concurrent.*;
 
public class ThreadPoolDemo {
 
    @Test
    public void test() throws InterruptedException, ExecutionException {
        //创建线程池对象
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.submit(() -> {
            System.out.println("开始");
            int i = 10 / 0;
            System.out.println("结束");
        });
    }
}

输出:

开始

submit 增加Future的get方法

import org.junit.Test;
 
import java.util.concurrent.*;
 
public class ThreadPoolDemo {
    @Test
    public void test() throws InterruptedException, ExecutionException {
        //创建线程池对象
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        Future future=singleThreadExecutor.submit(() -> {
            System.out.println("开始");
            int i = 10 / 0;
            System.out.println("结束");
        });
        Object o=future.get();
        singleThreadExecutor.shutdown();
    }
}
 

输出:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文