0

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?

Community
  • 1
  • 1
developer
  • 9,116
  • 29
  • 91
  • 150

3 Answers3

0
  1. Your "Calling thread ();" in java is thread.start();
  2. All threads run in the same java process
  3. No, the thread does not need to complete before the return statement happens.
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
0

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.

Community
  • 1
  • 1
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
0

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

Community
  • 1
  • 1
BernardMarx
  • 916
  • 8
  • 17