//No parameters, join(0) is called by default
public final void join() throws InterruptedException {
join(0);
}
//Pass in the two times millis milliseconds + nanos nanoseconds, which means wait for millis + nanos, and finally call method 3
public final synchronized void join(long millis, int nanos)
throws InterruptedException {
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos >= 500000 || (nanos != 0 && millis = = 0)) {
millis++;
}
join(millis);
}
//Method 3: Pass in the waiting time, in milliseconds, and call the underlying wait(time) of Object
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);//Indicates waiting forever, directing the thread to die
}
} else {
while ( isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public class ThreadJoin extends Thread {
public void run(){
try {
this.sleep(500);
System.out.println("["+new Date()+"]"+this.getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
int length = 5;
Thread[] threads = new Thread[length];
for(int i=0; i
threads[i] = new ThreadJoin();
threads[i].start() ;
threads[i].join();//join is called after each thread is started
}
long endTime=System.currentTimeMillis();
}
}
/*
output:
[Sun Jun 11 13:40:42 CST 2017]Thread-0
[Sun Jun 11 13:40:43 CST 2017]Thread-1
[Sun Jun 11 13:40:43 CST 2017]Thread-2
[Sun Jun 11 13:40:44 CST 2017]Thread-3
[Sun Jun 11 13:40:44 CST 2017]Thread-4
If you comment out join()
the result may be different every time
[Sun Jun 11 13:51:09 CST 2017]Thread-2
[Sun Jun 11 13:51:09 CST 2017]Thread-4
[Sun Jun 11 13:51:09 CST 2017]Thread-1
[Sun Jun 11 13 :51:09 CST 2017]Thread-3
[Sun Jun 11 13:51:09 CST 2017]Thread-0
*/
Don’t be hasty when doing things. After giving yourself a general direction, you have to take it step by step
The above is the detailed content of Thread--Introduction to the join() method. For more information, please follow other related articles on the PHP Chinese website!