/*线程的强制运行:join()方法*/
class MyThread4 implements Runnable{
public void run(){
for(int i=0; i<15; i++){
System.out.println(Thread.currentThread().getName()+"运行"+i);
}
}
}
public class ThreadJoin {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread4 mt = new MyThread4();
Thread th = new Thread(mt,"线程A");
th.start();
for(int i=0; i<25; i++){
if(i>7){
try {
th.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("xiancheng"+i);
}
}
}
/*
运行结果:
xiancheng0
xiancheng1
xiancheng2
xiancheng3
xiancheng4
xiancheng5
xiancheng6
xiancheng7
线程A运行0
线程A运行1
线程A运行2
线程A运行3
线程A运行4
线程A运行5
线程A运行6
线程A运行7
线程A运行8
线程A运行9
线程A运行10
线程A运行11
线程A运行12
线程A运行13
线程A运行14
xiancheng8
xiancheng9
xiancheng10
xiancheng11
xiancheng12
xiancheng13
xiancheng14
xiancheng15
xiancheng16
xiancheng17
xiancheng18
xiancheng19
xiancheng20
xiancheng21
xiancheng22
xiancheng23
xiancheng24
*/
class MyThread4 implements Runnable{
public void run(){
for(int i=0; i<15; i++){
System.out.println(Thread.currentThread().getName()+"运行"+i);
}
}
}
public class ThreadJoin {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread4 mt = new MyThread4();
Thread th = new Thread(mt,"线程A");
th.start();
for(int i=0; i<25; i++){
if(i>7){
try {
th.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("xiancheng"+i);
}
}
}
/*
运行结果:
xiancheng0
xiancheng1
xiancheng2
xiancheng3
xiancheng4
xiancheng5
xiancheng6
xiancheng7
线程A运行0
线程A运行1
线程A运行2
线程A运行3
线程A运行4
线程A运行5
线程A运行6
线程A运行7
线程A运行8
线程A运行9
线程A运行10
线程A运行11
线程A运行12
线程A运行13
线程A运行14
xiancheng8
xiancheng9
xiancheng10
xiancheng11
xiancheng12
xiancheng13
xiancheng14
xiancheng15
xiancheng16
xiancheng17
xiancheng18
xiancheng19
xiancheng20
xiancheng21
xiancheng22
xiancheng23
xiancheng24
*/

本文通过一个具体的Java代码示例介绍了线程中join方法的使用方式及其效果。通过主线程等待子线程完成后再继续执行的过程,展示了join方法如何帮助实现线程间的同步。
4170

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



