我们可以通过Thread.crrentThread()方法来获得当前的执行线程, 并获取线程中的各种信息。
线程id
一个随线程创建而递增的Long值
线程name
线程的名字,可以通过setName()指定
线程状态:getState()获得当前线程的状态,返回值是一个枚举类型
public enum State {
/**
* 当线程创建后还未调用start()时
*/
NEW,
/**
* 处于可执行状态的线程(已在执行中,或正等待cpu资源)
*/
RUNNABLE,
/**
* 阻塞状态:线程正等待synchronized代码块的锁资源
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,
/**
* 线程执行结束
*/
TERMINATED;
}
是否未daemon(守护)线程:
daemon线程在java是起辅助作用的线程,当所有非daemon线程结束时,java程序结束。
一个java程序至少有一个用于垃圾回收的daemon线程
public final void setDaemon(boolean on)
public final boolean isDaemon()
睡眠指定毫秒数,但不释放锁资源
public static native void sleep(long millis) throws InterruptedException
睡眠指定毫秒数和纳秒数,但不释放锁资源
public static void sleep(long millis, int nanos) throws InterruptedException
建议cpu当前线程不急于执行,可先执行其他线程
public static native void yield();
在指定时间内等待调用该方法的线程结束,等待时释放锁资源
public final synchronized void join(long millis)throws InterruptedException
在指定时间内等待调用该方法的线程结束,等待时释放锁资源
public final synchronized void join(long millis, int nanos) throws InterruptedException
等待调用该方法的线程结束,等待时释放锁资源
public final void join() throws InterruptedException