线程联合join
join() 方法的作用是调用线程等待该线程完成后,才能继续用下运行。
下面我写了一个简单例子,用来体现出join()方法是如何使用的。
package com.yzy.text;
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
Thread one = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":---"+i);
}
}
});
Thread two = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":---"+i);
}
}
});
/**
* 顺序执行
* **/
//one.start();
//one.join();
//two.start();
//two.join();
/**
* 并行执行
* **/
one.start();
two.start();
one.join();
two.join();
}
}
并行效果:
接下来把顺序执行的注释去掉,并将并行执行处加上注释,得到的效果:
顺序执行效果:
通过上面的例子可以体现出join的使用。
接下来来说说如何用join来实现线程联合的效果,下面是我的一个简单例子:
例子:
package com.yzy.text;
/*
* 线程联合 join (long mill,int namos)
* mill 毫秒
* namos 纳秒
* tourist.setName 设置线程名字
* */
class ThreadjoinTest implements Runnable{
Thread tourist,policeoffice; // tour 游客, policeoffice 警察局
public ThreadjoinTest() {
tourist = new Thread(this);
tourist.setName("咸鱼");
}
@Override
public void run() {
if (Thread.currentThread() == tourist) {
System.out.println("咸鱼计划去国外旅游!!!,需要去警察局办理护照。");
try {
Thread.sleep(1000);
policeoffice = new Thread(this);
policeoffice.start();
policeoffice.join(); //***线程联合 咸鱼线程停掉,它进行
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
System.out.println("咸鱼拿到护照,可以去签证了,准备出国");
}else if(Thread.currentThread() == policeoffice){
try {
System.out.println("咸鱼到了警察局填写申请表");
Thread.sleep(1000);
System.out.println("照相.......");
Thread.sleep(1000);
System.out.println("将申请表交给警察审核");
Thread.sleep(1000);
System.out.println("审核通过,交款,15天后取照");
Thread.sleep(2000);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
}
}
public class Text {
public static void main(String[] args) {
ThreadjoinTest tjt = new ThreadjoinTest();
tjt.tourist.start();
}
}
效果: