简体   繁体   中英

Thread.join() explanation

I am learning threads right now in school, and we had to write a program that used multiple threads, however, it did not work properly until I used thread.join()

It works like it should now, but I am not entirely sure what is happening.

Originally I had something like this. It caused the output of the threads to conflict with one another.

t1.start();
t2.start();
t3.start();

I then did this, and the output was fine and the correct answer was achieved.

 t1.start();
 t1.join();
 t2.start();
 t2.join();
 t3.start();
 t3.join();

My question is, what is happening in the first example compared to the second? I've been googling and searching on stackoverflow, but can not seem to find an answer that completely helps me understand.

t.join() causes the current thread to pause execution until t's thread terminates.

By doing this:

 t1.start();
 t1.join();
 t2.start();
 t2.join();
 t3.start();
 t3.join();

there is no reason to use threads...

thead.join() use example:

Lets say you need to encrypt 3 files, you want to use threads for faster processing time, and you want to know how much time it took:

int startTime = System.currentTimeMillis();
firstFileEncryptorThread.start();
secondFileEncryptorThread.start();
thirdFileEncryptorThread.start();

firstFileEncryptorThread.join();
secondFileEncryptorThread.join();
thirdFileEncryptorThread.join();

System.out.println(System.currentTimeMillis() - startTime );

As a javadoc:

Waits for this thread to die. An invocation of this method behaves in exactly the same way as the invocation

So when you call t1.join(); the thread in wich you've make the call wait to t1 to finish before executing the next line. If t1 never finish, the next line will never be executed.

The second example what you did is actually similar to single thread - meaning your run a thread , wait for it to finish and than run the next thread.

public final void join(): This java thread join method puts the current thread on wait until the thread on which it's called is dead. If the thread is interrupted, it throws InterruptedException.

In the first example - all thread are running in parallel

Can see similar question here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM