面試系列——java並發
一、使用線程
有三種使用線程的方法:
- 實現Runnable接口
- 實現Callable接口
- 繼承Thread類
實現 Runnable 和 Callable 接口的類只能當做一個可以在線程中運行的任務,不是真正意義上的線程,因此最后還需要通過 Thread 來調用。可以理解為任務是通過線程驅動從而執行的。
實現Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
// ...
}
}
使用Runnable實例再創建一個Thread實例,然后調用Thread實例的start方法來啟動線程。
public static void main(String[] args) {
MyRunnable instance = new MyRunnable();
Thread thread = new Thread(instance);
thread.start();
}
實現Callable接口
與Runnable相比,Callable可以有返回值,返回值通過FutureTask進行封裝
public class MyCallable implements Callable<Integer> {
public Integer call() {
return 123;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
繼承 Thread 類
同樣是需要實現run()方法,因為Thread類也實現了Runable接口。
當調用start()方法啟動一個線程時,虛擬機會將該線程放入就緒隊列中等待被調度,當一個線程被調度時會執行該線程的run方法。
public class MyThread extends Thread {
public void run() {
// ...
}
}
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
實現接口VS繼承Thread
實現接口會更好一些,因為:
- java不支持多重繼承,因此繼承了Thread類就無法繼承其他類,但是可以實現多個接口
- 類可能只要求可執行就行,繼承整個Thread類開銷過大。
二、基礎線程機制
線程池有什么作用?
線程池作用就是限制系統中執行線程的數量。
1、提高效率 創建好一定數量的線程放在池中,等需要使用的時候就從池中拿一個,這要比需要的時候創建一個線程對象要快的多。
2、方便管理 可以編寫線程池管理代碼對池中的線程統一進行管理,比如說啟動時有該程序創建100個線程,每當有請求的時候,就分配一個線程去工作,如果剛好並發有101個請求,那多出的這一個請求可以排隊等候,避免因無休止的創建線程導致系統崩潰。
Executor
Executor管理多個異步任務的執行,而無需程序員顯式地管理線程的生命周期。這里的異步是指多個任務的執行互不干擾,不需要進行同步操作。
主要有三種Executor:
- CachedThreadPool:一個任務創建一個線程,無限擴大,適合輕負載。
- FixedThreadPool:所有任務只能使用固定大小的線程,固定線程池,適合重負載。
- SingleThreadExecutor:相當於大小為1的FixedThreadPool.創建單線程的線程池,適用於需要保證順序執行各個任務。
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
executorService.execute(new MyRunnable());
}
executorService.shutdown();
}
Daemon
守護線程是程序運行時在后台提供服務的線程,不屬於程序中不可或缺的部分。
當所有非守護線程結束時,程序也就終止,同時會殺死所有守護線程。
mian()屬於非守護線程。
在線程啟動之前使用setDaemon()方法可以將一個線程設置為守護線程。
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
}
sleep()
Thread.sleep(millisec)方法會休眠當前正在執行的線程,millisec單位為毫秒。
sleep()可能會拋出InterruptedExecption,因為異常不能跨線程傳播回main()中,因此必須在本地處理。線程中拋出的其他異常也同樣需要在本地進行處理。
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
三、中斷
一個線程執行完畢之后會自動結束,如果在運行過程中發生異常也會提前結束。
InterruptedExecption
通過調用一個線程的interrupt()來中斷該線程,如果該線程處於阻塞、限期等待或者無限期等待狀態,那么就會拋出InterruptedException,從而提前結束該線程。但是不能中斷I/O阻塞和suynchronized鎖阻塞。
對於以下代碼,在main()中啟動一個線程之后再中斷它,由於線程中調用了Thread.sleep()方法, 因此會拋出一個 InterruptedException,從而提前結束線程,不執行之后的語句。
public class InterruptExample {
private static class MyThread1 extends Thread {
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new MyThread1();
thread1.start();
thread1.interrupt();
System.out.println("Main run");
}
Main run
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at InterruptExample.lambda$main$0(InterruptExample.java:5)
at InterruptExample$$Lambda$1/713338599.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Executor 的中斷操作
調用Executor的shutdown()方法會等待線程都執行完畢之后再關閉,但是如果調用的是shutdownNow()方法,則相當於調用每個線程的interrupt()方法。
以下使用Lambda創建線程,相當於創建了一個匿名內部線程。
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.shutdownNow();
System.out.println("Main run");
}
Main run
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)
at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
如果只想中斷 Executor 中的一個線程,可以通過使用 submit() 方法來提交一個線程,它會返回一個 Future<?> 對象,通過調用該對象的 cancel(true) 方法就可以中斷線程。
Future<?> future = executorService.submit(() -> {
// ..
});
future.cancel(true);
四、互斥同步
java提供了兩種鎖機制來控制多個線程對共享資源的互斥訪問,第一個是JVM實現的synchronized,而另一個是JDK實現的ReentrantLock。
synchronized
1、同步一個代碼塊
public void func() {
synchronized (this) {
// ...
}
}
它只作用於同一個對象,如果調用兩個對象上的同步代碼塊,就不會進行同步。
對於以下代碼,使用 ExecutorService 執行了兩個線程,由於調用的是同一個對象的同步代碼塊,因此這兩個線程會進行同步,當一個線程進入同步語句塊時,另一個線程就必須等待。
public class SynchronizedExample {
public void func1() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
}
}
}
public static void main(String[] args) {
SynchronizedExample e1 = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func1());
executorService.execute(() -> e1.func1());
}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
對於一下代碼,兩個線程調用了不同對象的同步代碼塊,因此這兩個線程就不需要同步。從輸出結果看出,兩個線程交叉執行。
public static void main(String[] args) {
SynchronizedExample e1 = new SynchronizedExample();
SynchronizedExample e2 = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func1());
executorService.execute(() -> e2.func1());
}
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
2、同步一個方法
public synchronized void func () {
// ...
}
它和同步代碼塊一樣,作用於同一個對象
3、同步一個類
public void func() {
synchronized (SynchronizedExample.class) {
// ...
}
}
作用於整個類,也就是說兩個線程調用同一個類的不同對象上的這種同步語句,也會進行同步。
public class SynchronizedExample {
public void func2() {
synchronized (SynchronizedExample.class) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
}
}
}
public static void main(String[] args) {
SynchronizedExample e1 = new SynchronizedExample();
SynchronizedExample e2 = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func2());
executorService.execute(() -> e2.func2());
}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
4、同步一個靜態方法
public synchronized static void fun() {
// ...
}
作用於整個類。
ReentrantLock
ReentrantLock是java.util.concurrent(J.U.C)包中的鎖。
public class LockExample {
private Lock lock = new ReentrantLock();
public void func() {
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
} finally {
lock.unlock(); // 確保釋放鎖,從而避免發生死鎖。
}
}
}
public static void main(String[] args) {
LockExample lockExample = new LockExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> lockExample.func());
executorService.execute(() -> lockExample.func());
}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
比較
1、鎖的實現
synchronized是JVM實現的,而ReentrantLock是JDK實現的。
2、性能
新版本java對synchronized進行了很多優化,例如自旋鎖等,synchronized與ReentrantLock大致相同。
3、等待可中斷
當持有鎖的線程長期不釋放鎖的時候,正在等待的線程可以選擇放棄等待,改為處理其他事情。
ReentrantLock 可中斷,而 synchronized 不行。
4、公平鎖
公平鎖是指多個線程在等待同一個鎖時,必須按照申請鎖的時間順序來依次獲得鎖。
synchronized 中的鎖是非公平的,ReentrantLock 默認情況下也是非公平的,但是也可以是公平的。
5、鎖綁定多個條件
一個 ReentrantLock 可以同時綁定多個 Condition 對象。
使用選擇
除非使用ReentrantLock的高級功能,否則優先使用synchronized。這是因為synchronized是JVM實現的一種鎖機制,JVM原生地支持,而ReentrantLock不是所有的JDK版本都支持。並且使用synchronized不用擔心沒有釋放鎖而導致死鎖問題,因為JVM會確保鎖的釋放。
五、線程協作
https://www.cnblogs.com/jimlau/p/12463663.html
六、線程狀態
https://www.cnblogs.com/jimlau/p/12463663.html