并发编程学习笔记(三)
说明:
本文内容来自java并发编程的艺术,仅仅为了学习时加深记忆。
线程简介
什么是线程
现代操作系统在运行一个程序时,会为其创建一个进程。现代操作系统调度的最小单元是线程,在一个进程里可以创建多个线程,这些线程都拥有各自的计数器、堆栈和局部变量等属性,并且能够访问共享的内存变量。处理器在这些线程上高速切换,让使用者感觉到这些线程在同时执行。
为什么使用多线程
-
更多的处理核心
程序运行过程中可以创建多个线程,而一个线程在一个时刻只能运行在一个处理器核心上。如果该程序使用多线程技术,将计算逻辑分配到多个处理器核心上,就会显著减少程序的处理时间,并且随着更多处理器核心的加入而变得更有效率。 -
更快的响应时间
可以使用多线程技术,将数据一致性不强的操作派发给其他线程处理,如生产订单快照、发送邮件等。这样做的好处是响应用户请求的线程能尽快地处理完成,缩短响应时间,提升了用户体验。 -
更好的编程模型
JAVA多线程提供了良好的编程模型,使开发人员能够更专注于问题的解决,
线程的状态
在给定的一个时刻,线程只能处于其中的一个状态。
状态名称 | 说明 |
---|---|
NEW | 初始状态,线程被构建,但是还没有调用start()方法 |
RUNNABLE | 运行状态,Java线程将操作系统中的就绪和运行两种状态笼统的称为“运行中” |
BLOCKED | 阻塞状态,表示线程阻塞与锁 |
WAITING | 等待状态,表示线程处于等待状态,进入该线程表示当前线程需要等待其它线程做出一些特定动作(通知或中断) |
TIME_WAITING | 超时等待状态,该状态不同于WAITING,它是可以在指定的时间自行返回的 |
TERMINATED | 终止状态,表示当前线程已经执行完毕 |
下面是用jstack工具(可以选择打开终端,键入jstack或者到JDK安装目录的bin目录下执行命令。)尝试查看示例代码运行时的线程信息,更加深入的理解线程状态。
import com.byj.suanfa.myythread.util.SleepUtils;
public class ThreadState {
public static void main(String[] args) {
new Thread(new TimeWaiting(),"TimeWaitingThread").start();
new Thread(new Waiting(),"WaitingThread").start();
new Thread(new Blocked(),"BlockedThread-1").start();
new Thread(new Blocked(),"BlockedThread-2").start();
}
//该线程不断的进行休眠
static class TimeWaiting implements Runnable{
@Override
public void run() {
while (true){
SleepUtils.second(100);
}
}
}
//该线程在waiting.class实例上等待
static class Waiting implements Runnable{
@Override
public void run() {
synchronized (Waiting.class){
try {
Waiting.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//该线程在Blocked.class实例上加锁后,不会释放该锁
static class Blocked implements Runnable{
@Override
public void run() {
synchronized (Blocked.class){
SleepUtils.second(100);
}
}
}
}
import java.util.concurrent.TimeUnit;
public class SleepUtils {
public static final void second(long seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
}
}
}
运行该实例,打开终端或者命令提示符,键入“jps”,输出如下:
由上图看到该程序所在进程id是26364,接着键入 jstack 26364,部分输出如下:
通过示例,我们了解到Java程序运行中线程线程状态的具体含义。线程在自身的生命周期中,并不是固定地处于某个状态,而是随着代码的执行在不同的状态之间进行切换。JAVA线程状态变迁如下图:
如上图可以看到,线程创建之后。调用start()方法开始运行。当线程执行wait()方法之后,线程进入等待状态。进入等待状态的线程要依靠其他线程的通知才能够返回到运行状态,而超时等待状态相当于在等待的基础上增加了超时的限制,也就是超时时间到达时将会返回到运行状态。当线程调用同步方法时,在没有获取到锁的情况下,线程将会进入到阻塞状态。线程在执行runnable的run()方法之后将会进入到终止状态。
Daemon线程
Daemon线程是一种支持型线程,因为它主要被用作程序中后台调度以及支持性工作。这意味着,当一个虚拟机中不存在非Daemon线程的时候,JAVA虚拟机将会退出。
可以通过Thread.setDaemon(true)将线程设置为Daemon线程。
Daemon属性需要在线程启动之前设置,不能在启动线程之后设置。
Daemon线程被用作完成支持性工作,但是在Java虚拟机退出时Daemon线程中的finally块并不一定执行。
public class Daemon {
public static void main(String[] args) {
Thread thread = new Thread(new DaemoRunner(), "DaemonRunner");
thread.setDaemon(true);
thread.start();
}
static class DaemoRunner implements Runnable{
@Override
public void run() {
try {
SleepUtils.second(10);
}finally {
System.out.println("DaemonThread finally run ");
}
}
}
}
运行Daemon线程时,可以看到终端或命令提示符上没有任何输出。
在构建Daemon线程时,不能依靠finnally块中的内容来确保执行关闭或清理资源的逻辑。
启动和终止线程
构造线程
在运行线程之前首先要构造一个线程对象,线程对象在构造时需要提供线程所需的属性,如线程组,线程优先级、是否未Daemon线程等信息。下图为java.lang.thread对线程进行初始化的部分。
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name.toCharArray();
//当前线程就是该线程的父线程
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
//将daemon\priority属性设置为父线程的对应属性
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
//将父线程的inheritableThreadLocals复制过来
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* 分配一个线程id/
tid = nextThreadID();
}
在上述过程中,一个新构造的线程对象是由其parent线程来进行空间分配的,而child线程继承了parent是否未Daemon、优先级和加载资源的contextClassLoder以及可继承的ThreadLocal,同时还分配了一个唯一的Id来标识这个child线程。至此,一个能够运行的线程对象就初始化好了,在堆内存中等待运行。
启动线程
线程start()方法的含义是:当前线程(即parent线程)同步告知Java虚拟机,只要线程规划器空闲,应立即启动调用start()方法的线程。
启动一个线程前,最好为这个线程设置线程名称,因为这样在使用jstack分析程序或进行问题排查时,就会给开发人员提供一些提示,自定义的线程最好能起个名字。
理解中断
中断可以理解为线程的一个标识位属性,它表示一个运行中的线程是否被其他线程进行了中断操作。中断好比其他线程对该线程打了个招呼,其他线程通过调用该线程的interrupt()方法对其进行中断操作。
线程通过检查自身是否被中断来进行响应,线程通过方法isInterrupted()来进行判断是否被中断,也可以调用静态方法Thread.interrupted对当前线程的中断标识进行复位。如果该线程处于终结状态,即使该线程被中断过,在调用该线程对象的isInterrupted时依旧会返回false.
从Java的API中可以看到,许多声明抛出InterruptedException的方法(例如Thread.sleep(long millis)方法)这些方法在抛出InterruptedException之前,Java虚拟机会先将该线程的中断标识位 清除,然后抛出InterruptedException,此时调用isInterrupted()方法将会返回false。
public class Interrupted {
public static void main(String[] args) {
Thread sleepThread = new Thread(new SleepRunner(), "SleepThread");
sleepThread.setDaemon(true);
Thread busyThread = new Thread(new BusyRunner(), "BusyThread");
busyThread.setDaemon(true);
sleepThread.start();
busyThread.start();
SleepUtils.second(5);
sleepThread.interrupt();
busyThread.interrupt();
System.out.println("SleepThread interrupted is " + sleepThread.isInterrupted());
System.out.println("BusyThread interrupted is " + busyThread.isInterrupted()); // 防止sleepThread和busyThread立刻退出
SleepUtils.second(2);
}
static class SleepRunner implements Runnable{
@Override
public void run() {
SleepUtils.second(10);
}
}
static class BusyRunner implements Runnable{
@Override
public void run() {
while (true){
}
}
}
输出如下:
安全的终止线程
上文提到的中断状态是线程的一个标识位,而中断操作时一种简便的线程间交互方式,而这种交互方式最适合用来取消或停止任务。除了中断外,还可以利用一个Boolean变量来控制是否需要停止任务并终止线程。
创建一个CountThread,它不断地进行变量累加,而主线程尝试对其进行终端操作和停止操作。
public class Shutdown {
public static void main(String[] args) {
Runner runner = new Runner();
Thread thread = new Thread(runner, "countThread");
thread.start();
SleepUtils.second(1);
thread.interrupt();;
Runner two = new Runner();
thread=new Thread(two,"countThread");
thread.start();
SleepUtils.second(1);
two.cancel();
}
private static class Runner implements Runnable{
private long i;
private volatile boolean on=true;
@Override
public void run() {
while (on&&!Thread.currentThread().isInterrupted()){
i++;
}
System.out.println("Count i ="+i);
}
public void cancel(){
on=false;
}
}
}
输出结果如下图:
示例在执行过程中,mian线程通过中断操作和cancel()方法均可以使countThread得以终止。这种通过标识为或者终端操作的方式都能使线程在终止时有有机会去清理资源,而不是武断地将线程停止,因此这种终止线程的做法显得更加优雅。
线程间的通信
volatile和synchronized关键字
Java支持多个线程同时访问一个对象或者对象的成员变量,由于每个线程可以拥有这个 变量的拷贝(虽然对象以及成员变量分配的内存是在共享内存中的,但是每个执行的线程还是 可以拥有一份拷贝,这样做的目的是加速程序的执行,这是现代多核处理器的一个显著特 性),所以程序在执行过程中,一个线程看到的变量并不一定是最新的。
关键字volatile可以用来修饰字段(成员变量),就是告知程序任何对该变量的访问均需要 从共享内存中获取,而对它的改变必须同步刷新回共享内存,它能保证所有线程对变量访问 的可见性。
举个例子,定义一个表示程序是否运行的成员变量boolean on=true,那么另一个线程可能 对它执行关闭动作(on=false),这里涉及多个线程对变量的访问,因此需要将其定义成为 volatile boolean on=true,这样其他线程对它进行改变时,可以让所有线程感知到变化,因为所 有对on变量的访问和修改都需要以共享内存为准。但是,过多地使用volatile是不必要的,因为 它会降低程序执行的效率。
关键字synchronized可以修饰方法或者以同步块的形式来进行使用,它主要确保多个线程 在同一个时刻,只能有一个线程处于方法或者同步块中,它保证了线程对变量访问的可见性 和排他性。
public class Synchronized {
public static void main(String[] args) {
synchronized (Synchronized.class){
}
m();
}
public static synchronized void m(){
}
}
通过使用javap工具查看生成的class文件信息来分析synchronized关键字的实现细节,执行java -v Synchronized.class,部分相关输出如下所示:
上面class信息中,对于同步块的实现使用了monitorenter和monitorexit指令,而同步方法则 是依靠方法修饰符上的ACC_SYNCHRONIZED来完成的。无论采用哪种方式,其本质是对一 个对象的监视器(monitor)进行获取,而这个获取过程是排他的,也就是同一时刻只能有一个 线程获取到由synchronized所保护对象的监视器。
任何一个对象都拥有自己的监视器,当这个对象由同步块或者这个对象的同步方法调用时,执行方法的线程必须先获取该对象的监视器才能进入同步块或同步方法,而没有获取到监视器(执行该方法)的线程将会被阻塞在同步块和同步方法的入口出,进入BLocked状态。
下图描述了对象、对象的监视器、同步队列和执行线程之间的关系:
等待/通知机制
等待/通知的相关方法是任意Java对象都具备的,因为这些方法被定义在所有对象的超类java.lang.Object上,方法和描述如下:
方法名称 | 描述 |
---|---|
notify() | 通知一个在对象上等待的线程,使其从wait()方法返回,而返回的前提是该线程获取到了对象的锁 |
notifyAll() | 通知所有等待在该对象上的线程 |
wait() | 调用该方法的线程进入WAITING状态,只有等待另外线程的通知或被中断才会返回,需要注意,调用wait()方法后,会释放对象的锁 |
wait(long) | 超时等待一段时间,这里的参数时间是毫秒,也就是等待长达n毫秒,如果没有通知就超时返回 |
wait(long,int) | 对于超时时间更细粒度的限制,可以达到纳秒 |
下面示例,创建了两个线程-------WaitThread和NotifyThread,前者检查flag是否为false,如果符合要求,进行后续操作,否则在lock山等待,后者在睡眠一段时间后对lock进行通知。
public class WaitNotify {
static boolean flag=true;
static Object lock=new Object();
static class Wait implements Runnable{
@Override
public void run() {
//加锁,拥有lock的Monitor
synchronized (lock){
//当条件不满足时,继续wait,同时释放了lock的锁
while (flag){
try {
System.out.println(Thread.currentThread() +
" flag is true. wait @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 条件满足时,完成工作
System.out.println(Thread.currentThread() + " flag is false. running @ " +
new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}
}
static class Notify implements Runnable{
@Override
public void run() {
//加锁,拥有lock的monitor
synchronized (lock){
//获取lock的锁,然后进行通知,通知时不会释放lock的锁
//直到当前线程释放了lock后,waitThread才能从wait方法中返回
System.out.println(Thread.currentThread() + " hold lock. notify @ "
+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
lock.notifyAll();
flag=false;
SleepUtils.second(5);
}
//再次加锁
synchronized (lock){
System.out.println(Thread.currentThread() + " hold lock again. sleep @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); SleepUtils.second(5);
}
}
}
public static void main(String[] args) {
Thread waitThread = new Thread(new Wait(), "WaitThread");
waitThread.start();
SleepUtils.second(1);
Thread notifyThread = new Thread(new Notify(), "NotifyThread");
notifyThread.start();
}
}
执行结果如下:
该结果的第三行和第四行是可能会互换。上述例子主要说明了调用wait(),notify(),notifyAll()需要注意的细节,如下:
- 使用wait()、notify()和notifyAll()时需要先对调用对象加锁。
- 调用wait()方法后,线程状态由runnable变为Waiting,并将当前线程放置到对象的等待队列。
- notify()或notifyAll()方法调用后,等待线程依旧不会从wait()返回,需要调用notify()或notifyAll()的线程释放锁之后,等待线程才有机会从wait()返回。
- notify()方法将等待队列中的一个等待线程从等待队列中移到同步队列中,而notifyAll()方法则是将等待队列中所有的线程全部移到同步队列,被移动的线程状态由waiting变为blocked。
- 从wait()方法返回的前提是获得了调用对象的锁。
从上例可以看出,等待/通知机制依托于同步机制。其目的就是确保等待线程从wait()方法返回时能够感知到通知线程对变量做出的修改。(不太理解这句话)
WaitThread首先获取了对象的锁,然后调用对象的wait()方法,从而放弃了锁 并进入了对象的等待队列WaitQueue中,进入等待状态。由于WaitThread释放了对象的锁,
NotifyThread随后获取了对象的锁,并调用对象的notify()方法,将WaitThread从WaitQueue移到 SynchronizedQueue中,此时WaitThread的状态变为阻塞状态。NotifyThread释放了锁之后, WaitThread再次获取到锁并从wait()方法返回继续执行
Thread.join()的使用
如果在threadB中调用threadA执行了threadA.join()语句,其含义是threadA等待threadB线程终止后从threadA.join()语句返回。
以下示例,创建了10个线程,编号0~9,每个线程调用前一个线程的join方法,也就是线程0结束了,线程1才能从join方法中返回,而线程0需要等待main线程的结束。
public class Join {
public static void main(String[] args) {
Thread previous = Thread.currentThread();
for(int i=0;i<10;i++){
//每个线程拥有当前一个线程的引用,需要等待前一个线程的终止,才能从等待中返回
Thread thread = new Thread(new Domino(previous), String.valueOf(i));
thread.start();
previous=thread;
}
SleepUtils.second(5);
System.out.println(Thread.currentThread().getName()+" terminate.");
}
static class Domino implements Runnable{
private Thread thread;
public Domino(Thread thread){
this.thread=thread;
}
@Override
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" terminate.");
}
}
}
执行结果如下:
ThreadLocal的使用
ThreadLocal,即线程变量,是一个以ThreadLocal对象为键,任意对象为值的存储结构。这个结构被附带在线程上,也就是说一个线程可以根据一个ThreadLocal对象查询到绑定在这个线程上的值。
以下代码构建了一个Profiler类,它具有begin()和end()两个方法,而end()方法返回从begin()方法调用开始到end()方法被调用时的时间差,单位是毫秒。
public class Profiler {
//第一次get()方法调用时会进行初始化(如果set()方法没有调用),每个线程会调用一次
private static final ThreadLocal<Long> TIME_THREADLOCAL=new ThreadLocal<Long>(){
@Override
protected Long initialValue() {
return System.currentTimeMillis();
}
};
public static final void begin(){
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
public static final long end(){
return System.currentTimeMillis()-TIME_THREADLOCAL.get();
}
public static void main(String[] args) {
Profiler.begin();
SleepUtils.second(1);
System.out.println("Cost: "+Profiler.end()+" mills");
}
}
输出结构:
我感觉:
ThreadLocal就是和调用线程进行绑定,在调用get()方法时,会根据线程id找到对应的值。
等待超时模式
开发人员经常会遇到如下调用场景:
调用一个方法时等待一段时间(一般是给定一个时间段),如果方法能够在给定的时间段之内得到结果,那么将结果立刻返回,反之,超时返回默认结果。
j假设超时时间段是T,那么可以推断出在当前时间now+T之后会超时。
定义如下变量:
等待持续时间:RUEMAINING=T.
超时时间:FUTURE=now+T.
这时仅需要wait(RUEMAINING)即可,在wait(RUEMAINING)返回之后将会执行:RUEMAINING=FUTURE-now.如果RUEMAINING小于等于0,表示已经超时,直接退出,否则将继续执行wait(RUEMAINING).
伪代码如下:
一个简单的数据库连接池示例
使用了一个等待超时模式来构造一个简单的数据库连接池。在示例中模拟从连接池中获取、使用和释放连接的过程,而客户端获取连接的过程被设定为等待超时的模式。也就是在1000毫秒内如果无法获取到可用连接,就返回给客户端一个null.
首先是连接池的定义:
public class ConnectionPool {
private LinkedList<Connection> pool=new LinkedList<Connection>();
public ConnectionPool(int initialSize){
if(initialSize>0){
for(int i=0;i<initialSize;i++){
pool.addLast(ConnectionDriver.createConnection());
}
}
}
public void releaseConnection(Connection connection){
if(connection!=null){
//释放连接后需要进行通知,这样其他消费者就能够感知到连接池中已经归还了一个连接
synchronized (pool){
pool.addLast(connection);
pool.notifyAll();
}
}
}
//在mills内无法获取连接,将会返回null
public Connection fetchConnection(long mills) throws InterruptedException {
synchronized (pool){
if(mills<=0){
while (pool.isEmpty()){
pool.wait();
}
return pool.removeFirst();
}else{
long future=System.currentTimeMillis()+mills;
long remaining=mills;
while (pool.isEmpty()&&remaining>0){
pool.wait(remaining);
remaining=future-System.currentTimeMillis();
}
Connection result=null;
if(!pool.isEmpty()){
result=pool.removeFirst();
}
return result;
}
}
}
}
它通过构造函数初始化连接的最大上限,通过一个双向队列来维护连接,调用方需要先调用fetchConnection(long)方法来指定在多少毫秒内超时获取连接,当连接使用完成后,需要调用releaseConnection(Connection)方法将连接放回连接池。
public class ConnectionDriver {
static class ConnectionHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("commit")){
TimeUnit.MILLISECONDS.sleep(100);;
}
return null;
}
}
//创建一个Connection代理,在commit时休眠100毫秒。
public static final Connection createConnection(){
return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),new Class<?>[]{Connection.class},new ConnectionHandler());
}
}
public class ConnectionPoolTest {
static ConnectionPool pool=new ConnectionPool(10);
//保证ConnectionRunner能够同时开始
static CountDownLatch start=new CountDownLatch(1);
static CountDownLatch end;
static class ConnectionRunner implements Runnable{
int count;
AtomicInteger got;
AtomicInteger notGot;
public ConnectionRunner(int count,AtomicInteger got,AtomicInteger notGot){
this.count=count;
this.got=got;
this.notGot=notGot;
}
@Override
public void run() {
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
while (count>0){
try {
Connection connection = pool.fetchConnection(1000);
if(connection!=null){
try {
connection.createStatement();
connection.commit();
}finally {
pool.releaseConnection(connection);
got.incrementAndGet();
}
}else {
notGot.incrementAndGet();
}
} catch (InterruptedException | SQLException e) {
e.printStackTrace();
}finally {
count--;
}
}
end.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
int threadCount=20;
int count=200;
end=new CountDownLatch(threadCount);
AtomicInteger got = new AtomicInteger();
AtomicInteger notGot = new AtomicInteger();
for(int i=0;i<threadCount;i++){
Thread thread = new Thread(new ConnectionRunner(count, got, notGot),"connectionRunnerThread");
thread.start();
}
start.countDown();
end.await();
System.out.println("total invoke: " + (threadCount * count));
System.out.println("got connection: " + got);
System.out.println("not got connection " + notGot);
}
}
上面通过一个示例来测试简易数据库连接池的工作情况,模拟客户端ConnectionRunner获 取、使用、最后释放连接的过程,当它使用时连接将会增加获取到连接的数量,反之,将会增 加未获取到连接的数量。
上述示例中使用了CountDownLatch来确保ConnectionRunnerThread能够同时开始执行,并 且在全部结束之后,才使main线程从等待状态中返回。当前设定的场景是10个线程同时运行 获取连接池(10个连接)中的连接,通过调节线程数量来观察未获取到连接的情况。线程数、总 获取次数、获取到的数量、未获取到的数量以及未获取到的比率。