请参阅以下两个示例:
例1
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
//work
for (int i = 0 ; i < 5 ; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
executorService.execute(thread1);
executeService.shutdown();
}
实施例2
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
@Override
public void run() {
//work
for (int i = 0 ; i < 5 ; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
executeService.shutdown();
}
两种情况下的结果都相同,但是我的一个来自StackOverflow的朋友alexei-kaigorodov(在此问题中)在评论中说
“ executorService是替代的替代方法。将线程放入executorService是没有意义的。首先,创建Runnable,然后将其作为线程的参数并启动该线程,或者将可运行的变量提交给executorService。”
我希望我对我的问题很清楚,所以请告诉我将runnable传递给ExecuteService与将线程传递给ExecutableService的区别。
Thread implements Runnable
因此,求职者服务将接受它为simple Runnable
,从而调用该Thread.run()
方法。
这意味着它Thread
本身将永远不会启动,除非您start()
自己调用其方法,在这种情况下,结果是绝对不确定的。
因此,您可以说代码片段的行为相同,只是将a传递Runnable
给ExecutorService
,然后通过调用Runnable.run()
方法来执行它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句