如果不适用shutdown ,使用 executor执行任务时,就不能退出,也就不能键入控制台命令?线程与控制台之间有什么关系?
另由 控制台 返回,想到 java 的main ( ) 函数由于void,不需要写return 语句, 而 C 语言 main ( ) 函数由于 为int ,需要使用return ()? java 为什么可以这样设置,是出于什么样的机制?
伊谢尔伦2017-04-17 17:40:36
Thread
and Executor
are incommensurable. Thread
is the basic structure of Java
and represents the actual process in the program. The run
method of a thread is the thread execution process. Executor
is encapsulated on Thread
and introduces the concepts of thread pool and thread reuse to improve operating efficiency and save resources. Executor
controls the continuous running of the thread. Simply put, there is an infinite loop while(true) {} in the
, so the run
method of Thread
Thread
held by Executor
will keep running and will not stop. You need to use the shutdown
method to let Executor
Informs its subordinate Thread
to break out of the loop to stop the thread. Of course, Thread
does not have methods similar to shutdown
. Many programs require threads to continue running and will have loops. At this time, the inheritance and encapsulation of Thread
Sometimes, you need to implement the thread exit method yourself. Thread
和Executor
不可并论,Thread
是属于Java
的基础结构,代表的就是程序中实际的线程,其run
方法就是线程执行过程。Executor
是在Thread
上做了封装,引入了线程池和线程复用的概念以提高运行效率和节约资源。Executor
控制着线程持续运行,简单的说就是Thread
的run
方法里有一个无限循环while(true) {}
,所以Executor
所持有的Thread
会一直运行不会停止,需要使用shutdown
方法去让Executor
告知它下属的Thread
跳出循环以停止线程。当然,Thread
并非没有类似shutdown
的方法,很多程序需要线程持续运行,都会带有循环,这时候在继承封装Thread
的时候,都需要自行实现线程退出的方法。
关于Java
的main
返回void
的问题我想并没有什么特别好解释的,C
里的main
比较古老,那时候的程序还需要依赖返回值来告诉使用者程序是否正常运行,而Java
有健全的异常机制,程序也不直接基础控制台,所以即使要有返回值,也应该是Java Runtime
来做,而不是Java
main
of Java
returns void
, I don’t think there is anything particularly easy to explain. It is in C
main
is relatively old. At that time, programs still needed to rely on return values to tell users whether the program is running normally. However, Java
has a sound exception mechanism and the program does not directly control the basics. Taiwan, so even if there is a return value, it should be done by Java Runtime
, not the Java
program. 🎜