线程的几种状态
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
RUNNABLE
状态的线程正在 JVM 中执行,但它可能正在等待来自操作系统(如处理器)的其他资源。BLOCKED
状态的线程正在等待监视器锁以便进入同步代码块或同步方法,或者在调用Object.wait()方法后准备重入同步代码块或同步方法。WAITING
状态的线程正在等待另一个线程执行特定的动作,例如需要另一个线程调用Object.notify()
或者Object.notifyAll()
进行唤醒。当调用以下无参方法时,线程会进入WAITING
状态:Object.wait()
Thread.join()
LockSupport.park()
TIMED_WAITING
状态:Thread.sleep(millis)
Object.wait(timeout)
Thread.join(millis)
LockSupport.parkNanos(blocker, nanos)
LockSupport.parkUntil(blocker, deadline)
TERMINATED
状态。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
allowCoreThreadTimeOut
参数,则该参数的最小值可以为零。corePoolSize
时,该参数表示多余的空闲线程在终止之前等待新任务的最长时间。也就是说,如果多余的空闲线程在等待时间超过keepAliveTime
之后仍没有收到任务,则自动销毁。keepAliveTime
参数的时间单位。