1. 线程的状态回顾
线程从创建到最终的消亡,要经历若干个状态。一般来说,线程包括以下这几个状态:(原文更好理解,就不翻译了)
- New When we create a new Thread object using
new
operator, thread state is New Thread. At this point, thread is not alive and it’s a state internal to Java programming. - Runnable When we call
start()
function on Thread object, it’s state is changed to Runnable and the control is given to Thread scheduler to finish it’s execution. Whether to run this thread instantly or keep it in runnable thread pool before running it depends on the OS implementation of thread scheduler. - Running When thread is executing, it’s state is changed to Running. Thread scheduler picks one of the thread from the runnable thread pool and change it’s state to Running and CPU starts executing this thread. A thread can change state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run() method or waiting for some resources like IO,Network,etc.
- Blocked/Waiting A thread can be waiting for other thread to finish using thread
join
or it can be waiting for some resources to available, for example producer consumer problem (生产者-消费者问题)or waiter notifier implementation or IO resources, then it’s state is changed to Waiting. Once the thread wait state is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool. - Dead Once the thread finished executing, it’s state is changed to Dead and it’s considered to be not alive.
2. 线程生命周期中常用方法总结
2.1 sleep(long millis)
运行的线程调用sleep方法进入阻塞状态(不会释放任何对象锁),睡眠完之后继续进入就绪状态,等待线程调度。
public void sleepMethod() {
new Thread(new Runnable() {
@Override
public void run() {
try {
long start = System.currentTimeMillis();
Thread.sleep(2000);
long end = System.currentTimeMillis();
System.out.println(end -start);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
输出结果可能稍微大于2000ms。Thread.sleep() 和线程调度模块交互,将当前线程设置为阻塞状态,等待指定的时间。一旦等待时间结束,线程的状态切换为可执行状态,等待CPU的时间片轮转。所以等待的确切时间取决于操作系统的线程调度机制和定时器的精度。
注意:
1. 线程sleep期间,并没有失去此线程所获得的监视器(monitors)和锁(locks)。
2. 线程sleep期间,任何其他的线程抖可以中断此线程,一旦中断,则抛出InterruptedException.
2.2 join()
join()可以用来暂停当前线程的执行,让调用join()的线程强制运行完成或执行指定的时间。
public final void join()
public final synchronized void join(long millis)
public final synchronized void join(long millis, int nanos)
测试案例:
public void joinMethod() {
Thread thread1 = new Thread(new MyRunnable(), "thread1");
Thread thread2 = new Thread(new MyRunnable(), "thread2");
Thread thread3 = new Thread(new MyRunnable(),