如果子进程正在运行那么父进程将如何完成?
我在实现线程时遇到了疑问,所以想在取得一些进展之前先清除它。我有一个方法,从该方法中调用新线程,在下一行中我有 return 语句。
方法(){
调用线程();
返回语句;
}
这里会发生什么 我的意思是父进程是否在子进程之前完成?
I got a doubt while implementing threads, so thought of getting it cleared before i do some progress. I have a method from where the new thread is getting called and in the next line i have return statement.
Method(){
Calling thread ();
return statement;
}
What happens here? I mean Does the parent process completes before the child process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请查看这篇文章
make-parent-thread-wait -till-child-thread-completes-or-timeout
您需要使用
join
方法。您必须在父线程完成之前等待子线程完成。Kindly look at this post
make-parent-thread-wait-till-child-thread-completes-or-timeout
You need to use
join
method.You have to wait for the child thread to complete before parent completes.您似乎混淆了线程和进程的概念。 Java 程序在 Java 虚拟机中运行。该 JVM 是一个进程(可以在操作系统的任务管理器中查看)。一个进程可以“包含”多个进程。有关这方面的更多信息,请参阅这个讨论差异的问题。
为了回到你的问题,你的代码生成一个新线程并返回。线程实际执行的操作与调用方法无关。你问父进程是否先于子进程完成?好吧,这取决于。新线程有什么作用?如果速度非常快,那么也许不会。它们“并行”运行,这就是我们首先使用线程的原因。所以你不应该把你的逻辑建立在先完成的基础上。
想象一下你打电话给你的朋友并请他处理一些事情。给他打电话后,你继续做其他事情。通话已成功,您可以继续您的一天。你的朋友是你的新话题。也许你想稍后检查一切是否正常,但你不会在电话里等他处理。不使用线程时就会出现这种情况。
如果您认真对待 Java 并发,我强烈推荐 Java 并发实践
You seem to have the concepts of thread and process confused. A Java program runs in a Java Virtual Machine. This JVM is a process (viewable in the task manager of you operating system ). A process can "contain" multiple processes. More on this can be found reading this SO question that discusses the differences.
To get back to your question, you code spawns a new thread and returns. What the thread actually does, is of no concern to the calling method. You asked if the parent process completes before the child process? Well that depends. What does the new thread do? If it is very fast then maybe not. They are running "in parallel" which is why we use threads in the first place. So you shouldn't base your logic on what completes first.
Image you calling your friend and asking him to take care of something. After you have called him you continue doing other things. The call has succeded and you go on with your day. Your friend is your new thread. Maybe you want to check later if everything turned out ok, but you wouldn't wait on the phone while he takes cares of it. That would be the case when not using threads.
If you are serious about java concurrency I highly recommend Java Concurrency In Practice