Home  >  Article  >  Java  >  How to determine whether a thread has ended in java

How to determine whether a thread has ended in java

王林
王林Original
2020-05-15 11:55:185922browse

How to determine whether a thread has ended in java

We can add the thread to be judged to the current thread by calling the thread.Join() method, so that two alternately executing threads can be merged into sequential execution threads. If it executes successfully, it means that the thread has not ended.

(Video tutorial recommendation: java video)

For example, if the Join() method of thread A is called in thread B, it will not be executed until thread A completes execution. Continue executing thread B.

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

Specific code:

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线程结束
        }
    //}
}

Recommended tutorial: java entry program

The above is the detailed content of How to determine whether a thread has ended in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn