Tom*_*Tom 1 java multithreading
不确定我是否正确行事.我需要创建一个新线程来写出一定次数的消息.我认为这种方法到目前为止还不确定它是否是最好的方法.然后我需要在线程完成运行后显示另一条消息.我怎么做 ?使用isAlive()?我该如何实现?
public class MyThread extends Thread {
public void run() {
int i = 0;
while (i < 10) {
System.out.println("hi");
i++;
}
}
public static void main(String[] args) {
String n = Thread.currentThread().getName();
System.out.println(n);
Thread t = new MyThread();
t.start();
}
}
Run Code Online (Sandbox Code Playgroud)
直到现在你正在走上正轨.现在,要显示另一条消息,当此线程完成时,您可以Thread#join从主线程调用此线程.InterruptedException使用t.join方法时,您还需要处理.
然后你的主线程将继续,当你的线程t完成.所以,继续这样的主线程: -
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Your Message");
Run Code Online (Sandbox Code Playgroud)
当你t.join在一个特定的线程(这里是主线程)中调用时,那个线程将继续进一步执行,只有当线程t完成了它的执行时.