共计 2497 个字符,预计需要花费 7 分钟才能阅读完成。
在程序开发中, 一定遇到并发编程的场景, 虽然我们大部分时间并不直接使用 Thread, 但是 Thread 是多线程的基础, 面试中也会总是被问到与线程有关的问题; 那么线程都有哪些知识呢? 最近在研究线程的源码的时候也总结了关于线程一些基本知识;
线程是什么
线程是轻量级的进程, 是操作系统调度任务到 CPU 的最小单元;
多线程编程的优点
1、多线程编程能够最大程度的利用多核设备上面的 CPU 资源, 保证任务处理的足够快, 及时响应客户端的额请求
2、线程的创建的代价比创建进程的代价小很多, 同时多线程的上下文切换也更快;《操作系统概念 第六版》在 Solaris 2 上面, 创建进程比创建线程慢 30 倍, 而进程的上下文切换比线程的上下文切换慢 5 倍;
Java 中线程的状态有哪些
查看 java.lang.Thread 的源码有如下代码:
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;
}
1、NEW: 线程还没有启动的时候, 状态就是 NEW 即 新建状态
2、RUNNABLE: 当一个线程处于运行中或者等待 CPU 调度的时候, 状态就是 RUNNABLE 状态; 有些地方也称为 就绪状态
3、BLOCKED: 当一个线程在等待别的线程释放锁资源的时候, 状态就是 BLOCKED, 或者在该线程获取到锁之后, 在同步代码块里面调用了 Wait 方法, 这时候释放锁, 在获取到其他线程的 notify 或者 notifyAll 通知之后, 重新进入 同步代码块这段时间 该线程也是 BLOCKED 状态的;
4、WAITING: 当正在运行的线程调用了 Object.wait() 方法 或者 Thread.join() 方法 或者 LockSupport.park() 方法之后, 会进入到 WAITING 状态
5、TIMED_WAITING: 当正在运行的线程调用 Object.wait(n) 或者 Thread.join(n) 或者 LockSupport.parkUntil(blocker, n) 会进入到 TIMED_WAITING 状态
6、TERMINATED: 当线程结束后, 会进入到 TERMINATED 状态.
状态转换如下, 该图中比 Java 的状态多了一个 RUNNING 状态, 来区别 线程的就绪状态 与 运行状态 更加方便读者理解;
下面来看一下线程的状态转换用 Java 怎么实现: