thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
t.join(); //使调用线程 t 在此之前执行完毕。
public static int a = 0;
public void run() {
for (int k = 0; k < 5; k++) {
a = a + 1;
}
}
public static void main(String[] args) throws Exception {
Runnable r = new JoinTest();
Thread t = new Thread(r);
t.start();
System.out.println(a);
}
Java代码 收藏代码
public static void main(String[] args) throws Exception {
Runnable r = new JoinTest();
Thread t = new Thread(r);
t.start();
t.join(); //加入join()
System.out.println(a);
}
t.join(); //使调用线程 t 在此之前执行完毕。
t.join(1000); //等待 t 线程,等待时间是1000毫秒
public static int a = 0;
public void run() {
for (int k = 0; k < 5; k++) {
a = a + 1;
}
}
public static void main(String[] args) throws Exception {
Runnable r = new JoinTest();
Thread t = new Thread(r);
t.start();
System.out.println(a);
}
}
Java代码 收藏代码
public static void main(String[] args) throws Exception {
Runnable r = new JoinTest();
Thread t = new Thread(r);
t.start();
t.join(); //加入join()
System.out.println(a);
}
这个时候,程序输入结果始终为5。
本文深入解析Java线程中的Join方法,详细阐述其如何将两个交替执行的线程合并为顺序执行,并通过示例代码展示具体应用。重点分析了使用Join方法前后的输出结果差异,揭示了线程调度与同步机制的微妙之处。
191

被折叠的 条评论
为什么被折叠?



