Java并行基础
文章目录
进程和线程
进程是多个相关线程的集合,是程序执行的最小单位。使用多线程而不使用多进程设计并发程序的原因在于:线程之间的切换和调度成本远远小于进程。
线程的状态
- NEW:线程刚刚创建,还没有开始执行,等到调用
start()
方法时才会开始执行; - RUNNABLE:调用
start()
方法后,所有线程需要的资源已经准备就绪,线程进入RUNNABLE
状态; - BLOCKED:当线程遇到临界资源被占用,比如
synchrinized
代码块 ,就会进入BLOCKED
状态; - WAITING:进入一个无时间限制的等待,通常是一些特殊事件,比如通过
wait()
方法的线程等待notify()
,或者调用别的线程的join()
方法,那么当前线程就会无限等待直到别的线程执行完毕并返回; - TIMED_WAITING:进入一个有时限的等待,比如加了等待时长或
join
时间; - TERMINATED:线程执行完毕后进入终止状态。
线程控制
启动
public static void main(String[] args){
Thread t = new Thread(() -> System.out.println("Hello Thread!"));
t.satrt();
}
停止
Thread
提供了一个stop()
方法,可以暴力停止线程,但是stop()
是一个Deprecated
方法,后续版本可能会移除,因为这个方法太暴力了,假设一个线程正在修改一个数据,而且是分步骤的,这几个步骤相互独立并且没有事务管理,假设其中几个步骤执行完毕,调用了stop()
方法,那么由于后面的步骤未执行,就会导致数据不一致,这是很危险的操作。
解决这个问题,要么保证线程中的操作是原子操作,要么定义一个标记设置为volatile
,保证线程之间的可见性,在线程开始时(或while true
循环的开头)检查标记,一旦检测到停止,就不再执行后续操作了。
反正记住,停止千万不要用。
中断
咋一听中断和停止是一样的但并不是。中断只是给线程一个中断标志,表示有人通知这个线程需要停止了,然而你要不要停止,怎么响应这个通知,那是当事线程自己的事,跟其他人无关。
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
System.out.println("Hello interrupt!");
}
});
thread.start();
Thread.sleep(100);
thread.interrupt();
}
thread
线程会在调用interrupt()
方法后中断吗,答案是并不会,会一直打印,我们稍作修改:
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
if(Thread.currentThread().isInterrupted()){
System.out.println("Ai ya, wo bei da duan la~");
break;
}
System.out.println("Hello interrupt!");
}
});
thread.start();
Thread.sleep(100);
thread.interrupt();
}
这样程序就会在在中断时自己处理中断逻辑,但是千万不要在可能被中断的线程中调用sleep()
方法,否则如果程序正在sleep()
,突然收到中断通知,就会抛出InterruptedException
,而且会清除中断标志,所以如果在线程中catch了这个异常,就会导致程序中断异常,还是会继续执行下去,我们再改一下就好了:
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
if(Thread.currentThread().isInterrupted()){
System.out.println("Ai ya, wo bei da duan la~");
break;
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
System.out.println("Hello interrupt!");
}
});
thread.start();
Thread.sleep(100);
thread.interrupt();
}
这相当于是中断异常的时候捕获一下,重新打上中断标志。
中断相关的方法有三个:
Thread().interrupt()
:实例方法,通知线程中断;Thread().isInterrupted()
:实例方法,判断线程是否中断;Thread.interrupted()
:静态方法,判断当前线程的中断状态,并清除中断标志,可以用来接收中断标志并清除;
上面这个程序会一直输出public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { while (true) { if(Thread.currentThread().isInterrupted()){//中断标志不会被清除 //if(Thread.interrupted()){//接收一次中断信号,然后清除中断标志 System.out.println("Ai ya, wo bei da duan la~"); }else{ System.out.println("Hello interrupt!"); } } }); thread.start(); thread.interrupt(); }
Ai ya, wo bei da duan la~
,因为线程一旦被Thread().interrupt()
中断,中断标志会一直存在,但是如果使用Thread.interrupted()
中断就只会显示一次,然后继续正常执行。
等待(wait)和通知(notify)
wait()
和notify()/notifyAll()
方法并不是在Thread
类中,而是在Object
类中,这就意味着可以调用任何对象的这几个方法。
线程之间通过这些方法协作的过程是:如果在线程A
中调用了obj
对象的wait()
方法,那么线程A
就会暂停执行,然后加入到一个obj
对象的等待队列,如果还有别的线程调用了obj
对象的wait()
方法,也会加到这个等待队列当中;当别的线程调用了obj
对象的notify()
方法后,这个等待队列中的某一个线程会被唤醒继续执行,这个被唤醒的线程是随机的,并不遵循队列的先进先出;notifyAll()
方法是唤醒这个等待队列中的所有线程。
但是wait()/notify()/notifyAll()
方法并不能随便调用,它们必须包含在对应的synchronized
语句中,这几个方法在调用前都必须先获得obj
对象的监视器,调用完成后再释放监视器。
public class WaitNotifyTest {
private final static Object obj = new Object();
private final static int[] data = new int[2];
public static void main(String[] args) {
//t0线程计算完成后,通知t1线程开始执行
Thread t0 = new Thread(() -> {
synchronized (obj) {
try {
System.out.println("[" + LocalDateTime.now().toString() + "] t0 start...");
//模拟计算
Thread.sleep(2000L);
data[0] = 100;
data[1] = 20;
obj.notify();
System.out.println("[" + LocalDateTime.now().toString() + "] t0 end...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//t1线程的计算依赖于t0线程的结果,所以t1线程等待t0线程的通知
Thread t1 = new Thread(() -> {
synchronized (obj) {
try {
System.out.println("[" + LocalDateTime.now().toString() + "] t1 start...");
System.out.println("[" + LocalDateTime.now().toString() + "] wait for t0...");
obj.wait();
System.out.println("[" + LocalDateTime.now().toString() + "] t1 result: " + 1D * data[0] / data[1]);
System.out.println("[" + LocalDateTime.now().toString() + "] t1 end...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t0.start();
t1.start();
}
}
/**
* [2018-11-19T21:51:54.475] t1 start...
* [2018-11-19T21:51:54.475] wait for t0...
* [2018-11-19T21:51:54.475] t0 start...
* [2018-11-19T21:51:56.475] t0 end...
* [2018-11-19T21:51:56.475] t1 result: 5.0
* [2018-11-19T21:51:56.476] t1 end...
*/
wait()
方法和sleep()
方法都可以传入时间,达到等待固定时间的效果,但是后者不会占用或释放任何资源。
挂起(suspend)和恢复(resume)
这两个方法是Thread
类的实例方法,就是线程的暂停和恢复,这两个方法也是Deprecated
,原因和stop()
方法类似,stop()
是潜在的数据不一致风险,suspend()/resume()
是潜在的程序卡死(无限等待)风险。因为挂起的线程并不会释放资源,只有调用了该线程的resume()
方法,被占用的资源才有可能被释放。假设被挂起的线程没有被恢复(大多数情况下是意外),那么所有等待该线程释放资源的线程将无限等待下去,同时系统资源也会被占用,更糟糕的是,用jstack
打印堆栈信息,居然发现挂起线程的状态时RUNNABLE
,这给排查问题也带来了影响,所以不推荐使用这两个方法了。
public class WaitForever {
private final static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(() -> {
synchronized (object){
System.out.println("[" + LocalDateTime.now().toString() + "] t0 start...");
Thread.currentThread().suspend();
}
});
Thread t1 = new Thread(() -> {
synchronized (object){
System.out.println("[" + LocalDateTime.now().toString() + "] t1 start...");
Thread.currentThread().suspend();
}
});
t0.start();
//确保t1比t0后启动,由于t0挂起而且不释放资源,t1始终在等待资源释放,并没有执行
Thread.sleep(100L);
t1.start();
t0.resume();
//t1.resume()并没有生效,因为t0没有释放资源,t1 start后并没进入临界区
//所以调用t1.resume()的时候,t1线程并没有挂起,也就是t1.resume()调用先于t1.suspend()
//程序将永远不会停止,t1会永远被挂起
t1.resume();
t0.join();
t1.join();
}
}
/**
* [2018-11-19T22:22:04.344] t0 start...
* [2018-11-19T22:22:04.422] t0 end...
* [2018-11-19T22:22:04.422] t1 start...
*/
等待线程结束(join)和谦让(yield)
join()
是Thread
的实例方法,在线程A
中调用线程B
的join()
方法,表示线程A
愿意等待线程B
结束后在执行,和wait()/notify()
类似,可以用于线程依赖与另一个线程结果的场景;
yield()
方法是Thread
的静态方法,一旦在线程中调用了Thread.yield()
方法,就表示当前线程愿意让出CPU
资源,可以先让其他线程先执行,但并不意味着该线程不再往下执行,让出CPU资源后依然会争夺CPU资源,但是能不能争夺到CPU、什么时候继续执行就不一定了。
下面用join()
方法重新写上面的wait()/notify()
达到的效果:
public class WaitNotifyTest {
private final static int[] data = new int[2];
public static void main(String[] args) {
//t0线程计算完成后,通知t1线程开始执行
Thread t0 = new Thread(() -> {
System.out.println("[" + LocalDateTime.now().toString() + "] t0 start...");
//模拟计算
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
data[0] = 100;
data[1] = 20;
System.out.println("[" + LocalDateTime.now().toString() + "] t0 end...");
});
//t1线程的计算依赖于t0线程的结果,所以t1线程等待t0计算完成后再开始
Thread t1 = new Thread(() -> {
System.out.println("[" + LocalDateTime.now().toString() + "] t1 start...");
try {
System.out.println("[" + LocalDateTime.now().toString() + "] wait for t0...");
t0.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("[" + LocalDateTime.now().toString() + "] t1 result: " + 1D * data[0] / data[1]);
System.out.println("[" + LocalDateTime.now().toString() + "] t1 end...");
});
t0.start();
t1.start();
}
}
volatile
这个关键字在JMM里提到过,一是保证对所有线程的可见性,另一个就是禁止指令重排。下面写个简单的例子证明这个关键字是有效的:
public class VolatileTest {
private boolean close = false;
public void start() {
System.out.println("上班!");
Thread boss = new Thread(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("下班!");
close = true;
});
Thread waiter = new Thread(() -> {
while (!close);
});
waiter.start();
boss.start();
System.out.println("回家!");
}
public static void main(String[] args) throws InterruptedException {
new VolatileTest().start();
}
}
运行上面的程序,理想状态下是
上班!
服务员开始工作!
老板开始工作!
下班!
老板下班!
服务员下班!
回家!
但是运行上面的程序会发现,服务员一直在工作,根本不会下班,程序一直在运行,不会结束。这是因为服务员首先看了一眼门口的营业状态是:营业中,然后在小本本上记下了状态,开始工作,下次确认的时候并没有去看门口的标志,而是看了看手上的小本本,发现一直是营业中,就一直工作到猝死,即使boss已经更把标志翻过来变成了打烊,服务员并没有被通知到,也没有主动去更新,老板只管把状态改了,自己知道下班了,不管员工知不知道。
如果给营业状态前加上volatile
关键字,服务员就一定会下班,因为一旦加上volatile
关键字,一旦状态被更新,任何使用营业状态的服务员小本本上的状态都会被强制擦掉,这样服务员在小本本上看不到状态,就会重新去门口看,那么肯定就会下班。
public class VolatileTest {
//加上volatile关键字就一定会结束
private volatile boolean close = false;
public void start() {
System.out.println("上班!");
Thread boss = new Thread(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("下班!");
close = true;
});
Thread waiter = new Thread(() -> {
while (!close);
});
waiter.start();
boss.start();
System.out.println("回家!");
}
public static void main(String[] args) throws InterruptedException {
new VolatileTest().start();
}
}
但是volatile
关键字并不能保证原子性:
public class VolatileTest {
private static volatile int sum = 0;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 1; i <= 100; i++) {
int finalI = i;
executorService.submit(() -> sum += finalI);
}
executorService.shutdown();
while(!executorService.isTerminated()){
System.out.println("computing...");
}
System.out.println(sum);
}
}
打印的结果很大可能不是5050。
线程组
一系列相关的的线程可以分配在一个线程组中方便管理:
public class ThreadGroupTest {
public static void main(String[] args) {
ThreadGroup threadGroup = new ThreadGroup("FirstGroup");
Thread thread1 = new Thread(threadGroup, new MyThread(), "thread1");
Thread thread2 = new Thread(threadGroup, new MyThread(), "thread2");
Thread thread3 = new Thread(threadGroup, new MyThread(), "thread3");
thread1.start();
thread2.start();
thread3.start();
System.out.println("[" + LocalDateTime.now().toString() + "]active count: "+ threadGroup.activeCount());
threadGroup.list();
}
public static class MyThread extends Thread{
@Override
public void run() {
String groupName = Thread.currentThread().getThreadGroup().getName();
String threadName = Thread.currentThread().getName();
while (true){
System.out.println("[" + LocalDateTime.now().toString() + "][" + groupName + "-" + threadName + "] running...");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* [2018-11-24T15:59:16.415][FirstGroup-thread1] running...
* [2018-11-24T15:59:16.415][FirstGroup-thread3] running...
* [2018-11-24T15:59:16.415][FirstGroup-thread2] running...
* [2018-11-24T15:59:16.415]active count: 3
* java.lang.ThreadGroup[name=FirstGroup,maxpri=10]
* Thread[thread1,5,FirstGroup]
* Thread[thread2,5,FirstGroup]
* Thread[thread3,5,FirstGroup]
* [2018-11-24T15:59:18.416][FirstGroup-thread1] running...
* [2018-11-24T15:59:18.416][FirstGroup-thread2] running...
* [2018-11-24T15:59:18.416][FirstGroup-thread3] running...
* ...
*/
驻守后台:守护线程(Daemon)
守护线程和用户线程是相对的,跟它的名字一样,守护线程会在后台静默完成一些系统性的服务,比如GC线程、JIT线程等,这些线程没有什么具体的业务含义,当一个系统中只有守护线程的时候,整个Java虚拟机就会退出:
public class DamonTest {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true){
System.out.println("daemon thread running....");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.setDaemon(true);//设置为守护线程
thread.start();
Thread.sleep(5000L);
}
}
/**
* daemon thread running....
* daemon thread running....
* daemon thread running....
* daemon thread running....
* daemon thread running....
* Process finished with exit code 0
*/
上面的程序设置thread线为守护线程,一旦所有用户线程结束,这个线程将自动结束,虚拟机退出。如果不使用thread.setDaemon(true);
即使main方法执行完毕,thread依然会不停地打印daemon thread running....
。同时,设置守护线程必须在调用start()
方法之前,否则会抛出java.lang.IllegalThreadStateException
,线程依然是当做用户线程执行,不会在主线程结束后停止打印。
线程优先级
线程的优先级越高,在争夺资源的时候更有优势,这也不是绝对的,因为运气不好高优先级的线程也会抢占资源失败。这种控制是不精确的,各个平台、系统状态下表现都不一样,可能导致一个较低优先级的线程一直抢占不到资源,出现饿死的情况,因此优先级需要慎用,最好在应用层自己解决优先级问题。
Thread
类中有三个静态常量标识常用的线程优先级:
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
优先级只能在1-·0之间,数字越大优先级越高,越有可能争夺到资源。下面的例子模拟不同优先级线程执行的差别:一个线程组中有3个不同优先级的线程,每个线程都会争夺同一个资源,最终三个线程占用资源的次数是一样的,多运行几次,看看三个线程谁先结束:
public class ThreadPriorityTest {
public static void main(String[] args) {
ThreadGroup threadGroup = new ThreadGroup("FirstGroup");
Thread thread1 = new Thread(threadGroup, new MyThread(), "thread1");
Thread thread5 = new Thread(threadGroup, new MyThread(), "thread5");
Thread thread10 = new Thread(threadGroup, new MyThread(), "thread10");
thread1.setPriority(Thread.MIN_PRIORITY);
thread5.setPriority(Thread.NORM_PRIORITY);
thread10.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread5.start();
thread10.start();
System.out.println("[" + LocalDateTime.now().toString() + "]active count: "+ threadGroup.activeCount());
threadGroup.list();
}
public static class MyThread extends Thread{
@Override
public void run() {
String groupName = Thread.currentThread().getThreadGroup().getName();
String threadName = Thread.currentThread().getName();
int count = 0;
while (count < 100000000){
synchronized (ThreadPriorityTest.class){
count++;
}
}
System.out.println("[" + LocalDateTime.now().toString() + "][" + groupName + "-" + threadName + "] finish...");
}
}
}
/**
* [2018-11-24T16:27:58.931]active count: 3
* java.lang.ThreadGroup[name=FirstGroup,maxpri=10]
* Thread[thread1,1,FirstGroup]
* Thread[thread5,5,FirstGroup]
* Thread[thread10,10,FirstGroup]
* [2018-11-24T16:28:07.467][FirstGroup-thread10] finish...
* [2018-11-24T16:28:08.497][FirstGroup-thread5] finish...
* [2018-11-24T16:28:08.800][FirstGroup-thread1] finish...
* Process finished with exit code 0
*/
结果不总是按照优先级高的先完成,这也证明了前面说的优先级高的也不一定能百分百争夺到资源,但是多执行几次,高优先级的总是会倾向于先执行完毕。
线程安全与synchronized
什么是线程安全?每本书都有每本书的解释,每个人都有不同的描述,如果让我一句话来总结一下就是:多线程系统中,每次执行都能达到预期的结果,跟单线程执行结果一致。发散来讲又会提到原子性、可见性和一致性。
Java中保证线程安全有一个非常重要的关键字synchronized
,其工作原理是对可能产生线程安全的代码块加锁,使得每一次只有一个线程进入同步块,从而保证线程间的安全性。synchronized
的用法有:
- 指定加锁对象:进入同步块代码时,需要获得对象的锁;
- 直接作用与实例方法:相当于对当前实例加锁,进入方法前需要获得当前实例的锁;
- 直接作用于静态方法:相当于对当前类加锁,进入方法前需要获得当前类的锁。
public class SynchronizedTest {
private static int sum0 = 0;
private static int sum1 = 0;
private static int sum2 = 0;
private static int sum3 = 0;
private static int sum4 = 0;
private static int sum5 = 0;
private static int sum6 = 0;
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
sum0 += i;
}
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(() -> sum1 += finalI).start();
}
Object o = new Object();
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(() -> {
synchronized (o){
sum2 += finalI;
}
}).start();
}
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(new Thread(() -> incSum3(finalI))).start();
}
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(new Thread(() -> incSum4(finalI))).start();
}
SynchronizedTest test = new SynchronizedTest();
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(new Thread(() -> test.incSum5(finalI))).start();
}
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(new Thread(() -> test.incSum6(finalI))).start();
}
System.out.println("sum0 = " + sum0);//5050
System.out.println("sum1 = " + sum1);//不一定5050
System.out.println("sum2 = " + sum2);//5050
System.out.println("sum3 = " + sum3);//不一定5050
System.out.println("sum4 = " + sum4);//5050
System.out.println("sum5 = " + sum5);//不一定5050
System.out.println("sum6 = " + sum6);//5050
}
private static void incSum3(int inc){
sum3 += inc;
}
private static synchronized void incSum4(int inc){
sum4 += inc;
}
public void incSum5(int inc){
sum5 += inc;
}
public synchronized void incSum6(int inc){
sum6 += inc;
}
}
那么再看看下面的代码是否能保证线程安全:
public class ThreadI {
private static Integer sum = 0;
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
int finalI = i;
new Thread(() -> {
synchronized (sum){
sum += finalI;
}
}).start();
}
System.out.println(sum);
}
}
看起来是没有毛病的:每次累加前都获取sum的锁,这样就不会产生线程安全问题了,但是实际上结果并不一定是5050。原因是,Integer
等包装类和String
一样都是final
的不变对象,一旦创建就不能改变,那i++
或s += "abc"
是怎么实现的呢?本质是创建一个新的对象让它的值等于计算后的值,所以每次获取到的锁并不在同一个对象上,所以不能保证线程安全。
并发下的容器
ArrayList
:多个线程同时向ArrayList
中add元素,可能会出现不同的结果,运气好的话,和串行执行结果一致,更多情况下是元素个数不对,先后顺序不对,甚至数组越界(一个线程正在扩容,另一个线程没等扩容完毕就开始访问索引);HashMap
:多个线程同时向HashMap
中put元素,同样会出现三种可能的结果,第一种是正常结束,第二种是元素个数不对,因为hash冲突的时候,可能向桶里的同一位置插入元素,导致某一个节点丢失,最后一种情况相当危险,因为可能导致程序卡死甚至崩溃,原因在于桶里的链表在多线程情况下可能变成一个循环链表,在put操作时会遍历这个链表,如果是一个环,那么肯定死循环。但是Java8中已经不存在这样的情况了,因为Java8对HashMap做了很多优化规避了这个问题,但是多线程下仍然不能使用HashMap,最简单的解决办法就是使用ConcurrentHashMap
代替。