java Java中的main()方法和主线程是什么关系?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17669159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the relation between the main() method and main thread in Java?
提问by Java_begins
My tutor told me that the main thread is the parent thread of every thread, but he is not able to explain why.
我的导师告诉我主线程是每个线程的父线程,但他无法解释原因。
When I write a simple program:
当我写一个简单的程序时:
Class A{}
Then it at the time of execution it throws an exception:
然后它在执行时抛出异常:
java.lang.NoSuchMethodError: main Exception in thread "main"
Is there any relation between the main()
method and the main thread?
main()
方法和主线程之间有什么关系吗?
回答by Thilo
Is there any relation between main() method and Main Thread ?
main() 方法和 Main Thread 之间有什么关系吗?
When the JVM starts, it creates a thread called "Main". Your program will run on this thread, unless you create additional threads yourself.
当 JVM 启动时,它会创建一个名为“Main”的线程。您的程序将在此线程上运行,除非您自己创建其他线程。
The first thing the "Main" thread does is to look for your static void main(String[] argv)
method and invoke it. That is the entry-point to your program.
“主”线程做的第一件事是查找您的static void main(String[] argv)
方法并调用它。那是您的程序的入口点。
If you want things to happen "at the same time", you can create multiple threads, and give each something to execute. They will then continue to do these things concurrently. The JVM also creates some internal threads for background work such as garbage collection.
如果您希望事情“同时”发生,您可以创建多个线程,并给每个线程执行一些操作。然后他们将继续同时做这些事情。JVM 还会为后台工作(例如垃圾收集)创建一些内部线程。
回答by Jatin
Firstly Main Thread is a parent thread of every thread
is ambiguous. Unlike Process
, in Java threads there is no concept of parent and child. You do have ThreadGroups
to group Threads and then have child groups, but it is different from Process
in the sense that if parent dies, the child still remains.
首先Main Thread is a parent thread of every thread
是模棱两可。与 不同Process
,在 Java 线程中没有父子线程的概念。您确实必须ThreadGroups
对线程进行分组,然后再有子组,但这Process
与如果父级死亡,子级仍然存在的意义不同。
The main
thread is the thread that starts your program, or simply which runs your public static void main(String... args)
method.
该main
线程是启动程序,或者干脆是运行在该线程public static void main(String... args)
的方法。