在 Java 中连接线程
有时一个线程需要知道另一个线程何时终止。在 java 中, isAlive() 和 join() 是两种不同的方法,用于检查线程是否已经完成执行。
如果调用的线程仍在运行,则 isAlive() 方法返回真,否则返回假。
*final* boolean **isAlive()**
但是, join() 方法比 isAlive() 更常用。此方法等待,直到调用它的线程终止。
*final* void **join()** throws **InterruptedException**
使用 join() 方法,我们告诉我们的线程等待,直到指定的线程完成它的执行。 join() 方法有重载版本,允许我们指定等待指定线程终止的时间。
*final* void **join**(long *milliseconds*) throws **InterruptedException**
正如我们在多线程介绍中看到的,主线程必须始终是最后一个完成其执行的线程。因此,我们可以使用 Thread join()方法来确保程序创建的所有线程在主线程执行之前已经被终止。
Java isAlive
方法
让我们举个例子,看看isAlive()
方法是如何工作的。如果线程状态为活动,则返回 true,否则返回 false。
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie)
{
// do something
}
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
r1 真 r1 真 r2 真 r2
没有join()
方法的螺纹示例
如果我们在不使用 join()方法的情况下运行一个线程,那么线程的执行是无法预测的。线程调度器调度线程的执行。
public class **MyThread** extends **Thread**
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
r1 r1 r2 r2
在上面的程序中,创建了两个线程 t1 和 t2。t1 首先开始,在控制台上打印“r1”之后,线程 t1 进入睡眠状态 500 ms。同时,线程 t2 将开始其进程,并在控制台上打印“r1”,然后进入睡眠状态 500 ms。线程 t1 将从睡眠中醒来,并在控制台上打印“r2”类似地,线程 t2 将从睡眠中醒来,并在控制台上打印“r2”。所以你会得到类似r1 r1 r2 r2
的输出
使用join()
方法的螺纹示例
在这个例子中,我们使用 join()方法来确保线程在启动其他线程之前完成了它的执行。当我们想根据自己的需求执行多个线程时,这很有帮助。
public class **MyThread** extends **Thread**
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
**t1.start();**
try{
**t1.join();** *//Waiting for t1 to finish*
}catch(InterruptedException ie){}
**t2.start();**
}
}
r1 r2 r1 r2
在上面的程序中,线程 t1 上的 join()方法确保 t1 在线程 t2 启动之前完成它的处理。
使用联接指定时间()
如果在上面的程序中,我们在使用 join() 和 t1 的同时指定时间,那么 t1 将在该时间执行,然后 t2 将加入其中。
public class MyThread extends Thread
{
MyThread(String str){
super(str);
}
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
MyThread t1=new MyThread("first thread");
MyThread t2=new MyThread("second thread");
t1.start();
try{
t1.join(1500); //Waiting for t1 to finish
}catch(InterruptedException ie){
System.out.println(ie);
}
t2.start();
try{
t2.join(1500); //Waiting for t2 to finish
}catch(InterruptedException ie){
System.out.println(ie);
}
}
}
Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it.