search

Home  >  Q&A  >  body text

java中,分别使用 Thread 与 Executor执行任务,为什么前者不需要显式的退出,而后者需要shutdown ?

  1. 如果不适用shutdown ,使用 executor执行任务时,就不能退出,也就不能键入控制台命令?线程与控制台之间有什么关系?

  2. 另由 控制台 返回,想到 java 的main ( ) 函数由于void,不需要写return 语句, 而 C 语言 main ( ) 函数由于 为int ,需要使用return ()? java 为什么可以这样设置,是出于什么样的机制?

高洛峰高洛峰2886 days ago439

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦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 run method of Thread , so the 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. ThreadExecutor不可并论,Thread是属于Java的基础结构,代表的就是程序中实际的线程,其run方法就是线程执行过程。Executor是在Thread上做了封装,引入了线程池和线程复用的概念以提高运行效率和节约资源。Executor控制着线程持续运行,简单的说就是Threadrun方法里有一个无限循环while(true) {},所以Executor所持有的Thread会一直运行不会停止,需要使用shutdown方法去让Executor告知它下属的Thread跳出循环以停止线程。当然,Thread并非没有类似shutdown的方法,很多程序需要线程持续运行,都会带有循环,这时候在继承封装Thread的时候,都需要自行实现线程退出的方法。

    关于Javamain返回void的问题我想并没有什么特别好解释的,C里的main比较古老,那时候的程序还需要依赖返回值来告诉使用者程序是否正常运行,而Java有健全的异常机制,程序也不直接基础控制台,所以即使要有返回值,也应该是Java Runtime来做,而不是Java

    Regarding the problem that 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. 🎜

    reply
    0
  • Cancelreply