本文目录一览:
java获得当前线程有两种方法,第一种是Thread.currentThread();谁知道另外一种?
另外一种是实现Runnable接口,implements Runnable
这种方法有两个好处是
(1)适合多个相同程序代码的线程去处理同一资源的情况,把虚拟CPU(线程)同程序的代码,数据有效的分离,较好地体现了面向对象的设计思想。
(2)可以避免由于Java的单继承特性带来的局限。经常碰到这样一种情况,即当要将已经继承了某一个类的子类放入多线程中,由于一个类不能同时有两个父类,所以不能用继承Thread类的方式,那么,这个类就只能采用实现Runnable接口的方式了。
java获取当前线程状态。
java线程的状态有下面几种状态:
/**
* 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
*
* pA thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called ttObject.wait()/tt
* on an object is waiting for another thread to call
* ttObject.notify()/tt or ttObject.notifyAll()/tt on
* that object. A thread that has called ttThread.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;
java 如何获得线程池中正在执行的线程数
java中线程池的监控可以检测到正在执行的线程数。
通过线程池提供的参数进行监控。线程池里有一些属性在监控线程池的时候可以使用
taskCount:线程池需要执行的任务数量。
completedTaskCount:线程池在运行过程中已完成的任务数量。小于或等于taskCount。
largestPoolSize:线程池曾经创建过的最大线程数量。通过这个数据可以知道线程池是否满过。如等于线程池的最大大小,则表示线程池曾经满了。
getPoolSize:线程池的线程数量。如果线程池不销毁的话,池里的线程不会自动销毁,所以这个大小只增不+
getActiveCount:获取活动的线程数。
通过扩展线程池进行监控。通过继承线程池并重写线程池的beforeExecute,afterExecute和terminated方法,我们可以在任务执行前,执行后和线程池关闭前干一些事情。如监控任务的平均执行时间,最大执行时间和最小执行时间等。这几个方法在线程池里是空方法。如:
protected
void
beforeExecute(Thread
t,
Runnable
r)
{
}