本篇主要介绍一下Thread类的方法以及探究一下线程的状态。
首先,Thread类常用的静态方法:
1.Thread.activeCount(),得到存活的线程数,返回值是int类型;
2.Thread.holdsLock(Object obj),当前线程是否获得了指定的对象同步锁,返回值是boolean类型;
3.Thread.currentThread(),得到当前线程,返回值是个Thread对象,一般后面再接着调用getName()方法,得到当前线程的名字;
4.Thread.sleep(long millis),让当前线程睡眠指定时间,以毫秒为单位;
5.Thread.yield(),让当前释放掉调度器的调度,使得调度器重新调度,一般来说只有优先级比当前线程高或者至少跟当前线程优先级相同的线程才可能得到调度器的调用,否则还是该线程被调度器调用。
Thread类常用的非静态方法:
1.thread1.get/setName(),thread1.get/setPriority(),thread1.isAlive() 是否存活,thread1.isDaemon() 是否是后台线程,thread1.getState() 得到线程的状态,getTheadGroup() 得到线程组。
2.thread1.join():当前线程阻塞,等待thread1线程执行后再执行。
3.wait() 使当前线程等待,notify() 唤醒在此同步监视器上等待的单个线程,notifyAll() 唤醒在此同步监视器上等待的所有线程:这三个方法不是Thread类定义的,而是继承Object类得到的,这三个方法只能由同步监视器对象调用。synchronized同步方法,this就是同步监视器对象。synchronized同步代码块,synchronized后面括号里的对象就是同步监视器对象。
线程的状态:
在Thread类中有一个内部枚举State,里面有6个变量,用于描述线程的状态:
- public enum State {
- /**
- * Thread state for a thread which has not yet started.
- */
- NEW,
- /**
- * Thread state for a runnable thread. A thread in the runnable state is
- * executing in the Java virtual machine but it may be waiting for other
- * resources from the operating system such as processor.
- */
- RUNNABLE,
- /**
- * Thread state for a thread blocked waiting for a monitor lock. A thread in
- * the blocked state is waiting for a monitor lock to enter a synchronized
- * block/method or reenter a synchronized block/method after calling
- * {@link Object#wait() Object.wait}.
- */
- 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,
- /**
- * Thread state for a terminated thread. The thread has completed execution.
- */
- TERMINATED;
- }
线程有6种状态,NEW、RUNNABLE 、BLOCKED、WAITING、TIMED_WAITING、TERMINATED。