java中如何判断一个线程是否结束

我们可以通过调用thread.Join()方法,把要判断的线程加入到当前线程中,这样可以将两个交替执行的线程合并为顺序执行的线程。如果顺利执行,则说明该线程未结束。

(视频教程推荐:java视频

比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。

t.join();      //调用join方法,等待线程t执行完毕
t.join(1000);  //等待 t 线程,等待时间是1000毫秒。

具体代码

public class TestJoin implements Runnable {


    public static void main(String[] sure) throws InterruptedException {
        Thread t = new Thread(new TestJoin());
        long start = System.currentTimeMillis();
        t.start();
        t.join(1000);//等待线程t 1000毫秒
        System.out.println(System.currentTimeMillis()-start);//打印出时间间隔
        System.out.println(Main finished);//打印主线程结束
    }

    @Override
    public void run() {
       // synchronized (currentThread()) {
            for (int i = 1; i <= 5; i++) {
                try {
                    sleep(1000);//睡眠5秒,循环是为了方便输出信息
                } catch (InterruptedException e) {
                    e.printstacktrace();
                }
                System.out.println(睡眠 + i);
            }
            System.out.println(TestJoin finished);//t线程结束
        }
    //}
}

推荐教程:java入门程序

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...