线程
1. 线程基础
- 线程状态图

jdk中关于线程状态的定义
public enum State {
/**
* 刚创建的线程, 线程还未开始,需要调用start()
* 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,
/**
* 遇到synchronized块时,会进入阻塞状态
* 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,
/**
* 等待状态, watting会进入一个无时间限制的等待
* 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的线程不能再回到RUNNABLE状态
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}
- 线程的等待
wait(): 一个线程调用object.wait(), 那么他就会进入object对象的等待队列.
notify(): 当object.notify()方法被调用时, 系统就会从等待队列中,随机选择一个线程, 并将其唤醒. 注意,这个选择是不公平的,完全是随机的.
notifyAll(): notifyAll()被调用时, 系统会唤醒在等待队列中的所有等待的线程,而不是随机选择一个.
join(): 表示这个线程需要等待依赖线程执行完毕, 才能继续执行.
yield(): 静态方法, 一旦执行, 它会使当前线程让出CPU. 注意, 让出CPU并不代表当前线程不执行了;当前线程在让出CPU后, 还会进行CPU资源的争夺,但是是否能够再次被分配到,就不一定了.
- volatile
- 告诉虚拟机,这个变量极有可能被某些程序后者线程修改,为了确保这个变量被修改后,应该程序范围内的线程都能够“看到”这个改动, 虚拟机就必须采用一些特殊手段,保证这个变量的可见性.
不能代替锁, 也无法保证一些符合操作的原子性.
守护线程(
Daemon) 守护线程是一种特殊的线程, 就和它的名字一样, 它是系统的守护者, 在后台默默地完成一些系统性的服务, 比如垃圾回收线程、JIT线程.
5.synchronized
- 实现线程间的同步,对同步的代码加锁,使得每一次,只能有一个线程进入同步块, 从而宝成线程间的安全性.
- 保证线程间的可见性和有序性.