thread.join函数,java多线程中的join函数解析

时间:2023-03-10 05:20:03
thread.join函数,java多线程中的join函数解析

join函数的作用,是让当前线程等待,直到调用join()的 线程结束或者等到一段时间,我们来看以下代码

 package mian;

 public class simpleplela {
static void threadMessage(String message) {
String threadName =
Thread.currentThread().getName(); System.out.println(threadName+" "+message
);
} private static class MessageLoop
implements Runnable {
public void run(){ String importantInfo[] = {
"ONe",
"TWo",
"THREe",
"four"
};
try{
for(int i = 0;
i<importantInfo.length;
i++){
Thread.sleep(4000);
threadMessage(importantInfo[i]);
}
}
catch(InterruptedException e){
threadMessage("I was'nt done!");
}
}
}
public static void main(String args[])
throws InterruptedException {
long patience = 1000*10;
if(args.length>0){
try{
patience = Long.parseLong(args[0])*1000;
}catch(NumberFormatException e){
System.err.println("Argument must be an integer");
System.exit(1);
}
}
threadMessage("Starting MessageLoop Thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MEssageLoop Thread to finish");
while((t.isAlive())){
threadMessage("still waiting..."); t.join();
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
} }

输出如下

thread.join函数,java多线程中的join函数解析

 package mian;

 public class simpleplela {
static void threadMessage(String message) {
String threadName =
Thread.currentThread().getName(); System.out.println(threadName+" "+message
);
} private static class MessageLoop
implements Runnable {
public void run(){ String importantInfo[] = {
"ONe",
"TWo",
"THREe",
"four"
};
try{
for(int i = 0;
i<importantInfo.length;
i++){
Thread.sleep(4000);
threadMessage(importantInfo[i]);
}
}
catch(InterruptedException e){
threadMessage("I was'nt done!");
}
}
}
public static void main(String args[])
throws InterruptedException {
long patience = 1000*10;
if(args.length>0){
try{
patience = Long.parseLong(args[0])*1000;
}catch(NumberFormatException e){
System.err.println("Argument must be an integer");
System.exit(1);
}
}
threadMessage("Starting MessageLoop Thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MEssageLoop Thread to finish");
while((t.isAlive())){
threadMessage("still waiting..."); t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
} }

输出如下 我们分析一下,两段代码只有一行不一样。第一段是t.join(),会让当前线程(例子中为主线程)一直等待,知道t结束;

第二段是t.join(1000),会让当前线程等待1000毫秒,之后继续。

thread.join函数,java多线程中的join函数解析