作者:liuleyi | 来源:互联网 | 2023-10-10 18:59
join()方法的用法:
join()是主线程 等待子线程的终止。也就是在子线程调用了 join() 方法后面的代码,只有等到子线程结束了才能执行。
例子如下:
- public class Testimplements Runnable {
- private staticint a = 0;
- public void run() {
- for(int i=0;i<10;i++)
- {
- a = a + i;
- }
- }
-
- public staticvoid main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new Test());
- t1.start();
- System.out.print(a);
- }
- }
public class Test implements Runnable {
private static int a = 0;
public void run() {
for(int i=0;i<10;i++)
{
a = a + i;
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Test());
t1.start();
//Thread.sleep(10);
//t1.join();
System.out.print(a);
}
}
上面程序最后的输出结果是0,就是当子线程还没有开始执行时,主线程已经结束了。
- public class Testimplements Runnable {
- private staticint a = 0;
- public void run() {
- for(int i=0;i<10;i++)
- {
- a = a + i;
- }
- }
-
- public staticvoid main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new Test());
- t1.start();
- t1.join();
- System.out.print(a);
- }
- }
public class Test implements Runnable {
private static int a = 0;
public void run() {
for(int i=0;i<10;i++)
{
a = a + i;
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Test());
t1.start();
//Thread.sleep(10);
t1.join();
System.out.print(a);
}
}
上面程序的执行结果是45,就是当主线程运行到t1.join()时,先执行t1,执行完毕后在执行主线程余下的代码!
总结:join()方法的主要功能就是保证调用join方法的子线程先执行完毕再执行主线程余下的代码!