在Java中,如何确定线程是否正在运行?

76 java multithreading

如何确定线程是否正在运行?

Way*_*yne 85

Thread.isAlive()


Abd*_*med 28

您可以使用此方法:

boolean isAlive()
Run Code Online (Sandbox Code Playgroud)

如果线程仍处于活动状态,则返回true;如果线程已死,则返回false.这不是一成不变的.您需要对Thread类的对象的引用.

还有一个提示:如果您正在检查它的状态以使主线程在新线程仍在运行时等待,则可以使用join()方法.它更方便.


Cha*_*ara 18

我想你可以使用GetState() ; 它可以返回线程的确切状态.


小智 9

通过调用检查线程状态Thread.isAlive.


小智 6

确切地说,

Thread.isAlive() 如果线程已启动(可能尚未运行)但尚未完成其run方法,则返回true.

Thread.getState() 返回线程的确切状态.


Yas*_*ash 5

Thread.State枚举类和新的getState() API 用于查询线程的执行状态。

一个线程在给定的时间点只能处于一种状态。这些状态是虚拟机状态,不反映任何操作系统线程状态[ NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED]。

enum Thread.State扩展了 Enum 实现了Serializable , Comparable

  • getState()jdk5 - public State getState() {...} « 返回this线程的状态。此方法设计用于监视系统状态,而不是用于同步控制。

  • 的IsAlive() - public final native boolean isAlive(); « 返回,如果在调用它的线程还活着,否则返回。如果线程已启动且尚未死亡,则该线程处于活动状态。

java.lang.Threadsun.misc.VM.

package java.lang;
public class Thread implements Runnable {
    public final native boolean isAlive();

    // Java thread status value zero corresponds to state "NEW" - 'not yet started'.
    private volatile int threadStatus = 0;

    public enum State {
        NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;
    }

    public State getState() {
        return sun.misc.VM.toThreadState(threadStatus);
    }
}

package sun.misc;
public class VM {
    // ...
    public static Thread.State toThreadState(int threadStatus) {
        if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
            return Thread.State.RUNNABLE;
        } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
            return Thread.State.BLOCKED;
        } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
            return Thread.State.WAITING;
        } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
            return Thread.State.TIMED_WAITING;
        } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
            return Thread.State.TERMINATED;
        } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
            return Thread.State.NEW;
        } else {
            return Thread.State.RUNNABLE;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实施例java.util.concurrent.CountDownLatch执行多个线程并行地,在完成所有线程主线程执行之后。(直到并行线程完成它们的任务,主线程才会被阻塞。)

public class MainThread_Wait_TillWorkerThreadsComplete {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Main Thread Started...");
        // countDown() should be called 4 time to make count 0. So, that await() will release the blocking threads.
        int latchGroupCount = 4;
        CountDownLatch latch = new CountDownLatch(latchGroupCount);
        new Thread(new Task(2, latch), "T1").start();
        new Thread(new Task(7, latch), "T2").start();
        new Thread(new Task(5, latch), "T3").start();
        new Thread(new Task(4, latch), "T4").start();

        //latch.countDown(); // Decrements the count of the latch group.

        // await() method block until the current count reaches to zero
        latch.await(); // block until latchGroupCount is 0
        System.out.println("Main Thread completed.");
    }
}
class Task extends Thread {
    CountDownLatch latch;
    int iterations = 10;
    public Task(int iterations, CountDownLatch latch) {
        this.iterations = iterations;
        this.latch = latch;
    }
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");
        for (int i = 0; i < iterations; i++) {
            System.out.println(threadName + " : "+ i);
            sleep(1);
        }
        System.out.println(threadName + " : Completed Task");
        latch.countDown(); // Decrements the count of the latch,
    }
    public void sleep(int sec) {
        try {
            Thread.sleep(1000 * sec);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

@也可以看看