0
点赞
收藏
分享

微信扫一扫

任务提交方法submit和execute

苦茶如歌 2022-02-17 阅读 72
javaeclipse

线程池提供了2种任务提交方法submit和execute,一般通过submit提交任务是用于可以有返回值的时
候,通过execute提交的任务不能获取任务的执行结果。
execute的方法:

public class Test1 { 
	public static void main(String[] args) {
		ExecutorService es=Executors.newFixedThreadPool(3);
		es.execute(()->{ 
			for(int i=0;i<10;i++) {
				System.out.println("Hello "+i);
				try {
					Thread.sleep(200); 
				} catch (InterruptedException e) { 
					e.printStackTrace(); 
				} 
			} 
		}); 
		System.out.println("main..."); 
	} 
}

submit的方法:

public class Test2 {
	public static void main(String[] args) {
		ExecutorService es = Executors.newFixedThreadPool(3);
		es.submit(() -> {
			for (int i = 0; i < 10; i++) {
				System.out.println("Hello " + i);
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		System.out.println("main...");
	}
}
举报

相关推荐

0 条评论