Java multithreading-method join (installation)

Source: Internet
Author: User

For Java developers, multithreading should be a knowledge point that must be skilled in application, especially for developing Java-based products. This article will give an in-depth explanation of the knowledge points of Java multithreading. In the subsequent series, it will focus on the design idea, implementation and application of concurrent parallel packages provided by Professor Doug Lea in Java 5.

How can we get it deeper? My understanding is that there is a problem, not a general view. Therefore, this series mainly focuses on solving problems. Of course, I also hope that readers can come up with better solutions and more questions. Due to the limited level, if there are any errors, please raise them and discuss them together. In short, I hope that through this series we will have a deep understanding of Java multithreading to solve our actual development problems.

As a developer, I don't think it is necessary to discuss the basic knowledge of multithreading, such as what is a thread? How to create and so on, these knowledge points can be obtained through books and Google. This series focuses on how to deeply understand multithreading to help our normal development, such as how to implement the thread pool? How to Apply locks.

(1) What is the use of join? Simple answer: How to synchronize synchronization? How to implement it? The answer is as follows.

Since I started to use Java multithreading, I have never understood join. JDK: join public final void join (long millis) throws interruptedexception waits at most millis milliseconds for this thread to die. a timeout of 0 means to wait forever. do you understand this? It literally means waiting for a while until this thread dies. My question is whether the thread is its own thread or the thread that calls it. The code above:

Package concurrentstudy;
/**
*
* @ Author VMA
*/
Public class jointest {
Public static void main (string [] ARGs ){
Thread t = new thread (New runnableimpl ());
T. Start ();
Try {
T. Join (1, 1000 );
System. Out. println ("joinfinish ");
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();

}
}
}
Class runnableimpl implements runnable {

@ Override
Public void run (){
Try {
System. Out. println ("begin sleep ");
Thread. Sleep (1000 );
System. Out. println ("end Sleep ");
} Catch (interruptedexception e ){
E. printstacktrace ();
}

}
}
The result is:
Begin sleep
End sleep
Joinfinish
Now, when the main thread calls T. join, the main thread waits for T thread. The waiting time is 1000. What if T thread sleep 2000?
Public void run (){
Try {
System. Out. println ("begin sleep ");
// Thread. Sleep (1000 );
Thread. Sleep (2000 );
System. Out. println ("end Sleep ");
} Catch (interruptedexception e ){
E. printstacktrace ();
}

}
The result is:
Begin sleep
Joinfinish
End sleep
That is to say, the main thread only waits for 1000 milliseconds. No matter when t ends, if it is T. Join (), check the Code:
Public final void join () throws interruptedexception {
Join (0 );
}
That is to say, if it is T. Join () = T. Join (0) 0 JDK, a timeout of 0 means to wait forever literally means waiting forever, right?
It actually waits until t ends.
How is this implemented? Check the JDK code:
/**
* Waits at most <code> millis </code> milliseconds for this thread
* Die. A timeout of <code> 0 </code> means to wait forever.
*
* @ Param millis the time to wait in milliseconds.
* @ Exception interruptedexception if any thread has interrupted
* The current thread. The <I> interrupted status </I> of
* Current thread is cleared when this exception is thrown.
*/
Public final synchronized void join (long millis)
Throws interruptedexception {
Long Base = system. currenttimemillis ();
Long Now = 0;

If (millis <0 ){
Throw new illegalargumentexception ("timeout value is negative ");
}

If (millis = 0 ){
While (isalive ()){
Wait (0 );
}
} Else {
While (isalive ()){
Long Delay = millis-now;
If (delay <= 0 ){
Break;
}
Wait (Delay );
Now = system. currenttimemillis ()-base;
}
}
} In fact, the join method is implemented through wait (note: the method provided by the object ). When the main thread calls T. during the join operation, the main thread will get the t lock of the thread object (wait means to get the lock of the object), call the wait (wait time) of the object until the object wakes up the main thread, for example, after exiting.

This means that the main thread calls T. during the join operation, you must be able to get the lock of the thread t object. If you cannot get the lock, it cannot be wait. The just-opened example T. join (1000) does not indicate that the main thread waits for 1 second. If other threads obtain the t object lock before it waits, the waiting time is not 1 millisecond. Code introduction:

/*
* To change this template, choose tools | templates
* And open the template in the editor.
*/
Package concurrentstudy;
/**
*
* @ Author VMA
*/
Public class jointest {
Public static void main (string [] ARGs ){
Thread t = new thread (New runnableimpl ());
New threadtest (T). Start ();
T. Start ();
Try {
T. Join ();
System. Out. println ("joinfinish ");
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();

}
}
}
Class threadtest extends thread {

Thread thread;

Public threadtest (thread ){
This. Thread = thread;
}

@ Override
Public void run (){
Holdthreadlock ();
}

Public void holdthreadlock (){
Synchronized (thread ){
System. Out. println ("getobjectlock ");
Try {
Thread. Sleep (9000 );

} Catch (interruptedexception ex ){
Ex. printstacktrace ();
}
System. Out. println ("releaseobjectlock ");
}

}
}

Class runnableimpl implements runnable {

@ Override
Public void run (){
Try {
System. Out. println ("begin sleep ");
Thread. Sleep (2000 );
System. Out. println ("end Sleep ");
} Catch (interruptedexception e ){
E. printstacktrace ();
}

}
}

In the main method, use new threadtest (t ). start (); instantiate the threadtest thread object. In the holdthreadlock () method, it uses synchronized (thread) to obtain the thread object t lock and release it after sleep (9000, this means that even if
Main Method T. Join (1000), wait for a second, it must wait for the threadtest thread to release t lock before entering the wait method, its actual wait time is 9000 + 1000 MS
The running result is:
Getobjectlock
Begin sleep
End sleep
Releaseobjectlock
Joinfinish

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.