目錄
- 1. java執行緒的狀態
- 2.Daemon執行緒
- 3.執行緒的創建方式
- 4.synchronized關鍵字(實作執行緒同步)
- 5.sleep()方法和wait()方法的區別
- 6.執行緒通信:
- 7.lock
- 8、執行緒不安全的集合類
- 9.死鎖問題
- 10. 并發工具類
- 11、讀寫鎖
- 12.阻塞佇列
- 13.執行緒池
1. java執行緒的狀態
有6種,new、runnable、blocked、waiting、time_waiting、terminated,同一個時刻一個執行緒只可能處在其中的一個狀態,
java執行緒狀態變遷可以參考《java并發編程的藝術中的圖》或者查看原始碼Thread.State的注釋,
可以通過jstack和執行緒id查看運行的java執行緒狀態
2.Daemon執行緒
守護執行緒是一種支持型執行緒,主要用于程式中后臺調度等作業,
java虛擬機中如果沒有用戶執行緒就會退出,此時所有的守護執行緒都會立即終止,守護執行緒中的finally塊不一定會執行,
在執行緒沒有運行之前可以通過setDaemon()方法把執行緒設定為守護執行緒,
3.執行緒的創建方式
- 繼承Thread類:Thread類實作了Runable介面
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"run");
}
}
class MyThreadTest{
public static void main(String[] args) {
Thread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
- 實作Runnable介面
class MyThread2{
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" run");
}
},"執行緒A").start();
//lambda運算式
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" run");
},"執行緒B").start();
}
}
- 實作callable介面:
FutureTask是Runable介面的實作類,同時也有屬性依賴callable介面,可以用來方便的創建執行緒,
//執行緒的創建方式:實作callable介面
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//這里FutureTask構造器傳入的是callable介面的匿名實作類物件
FutureTask<Integer> futureTask = new FutureTask<>(() -> {
System.out.println(Thread.currentThread().getName() + " come in callable");
return 1024;
});
FutureTask<Integer> futureTask2 = new FutureTask<>(() -> {
System.out.println(Thread.currentThread().getName() + " come in callable");
return 200;
});
new Thread(futureTask,"執行緒A").start();
new Thread(futureTask2,"執行緒B").start();
while (!futureTask.isDone()){
System.out.println("wait...");
}
System.out.println(futureTask.get());
System.out.println(futureTask.get());
System.out.println(futureTask2.get());
System.out.println(Thread.currentThread().getName()+" come over");
}
}
- 執行緒池創建:
execute()方法
4.synchronized關鍵字(實作執行緒同步)
- synchronized鎖的實作基礎:java中的每一個物件都可以作為鎖,
當一個執行緒試圖訪問同步代碼塊,它必須先得到鎖,退出或者拋出例外時必須釋放鎖,
public class SaleTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0 ; i < 30; i++) {
ticket.sale();
}
}
},"執行緒1").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0 ; i < 30; i++) {
ticket.sale();
}
}
},"執行緒2").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0 ; i < 30; i++) {
ticket.sale();
}
}
},"執行緒3").start();
}
}
class Ticket{
private int number = 30;
public synchronized void sale() {
if (number > 0) {
System.out.println(Thread.currentThread().getName()+"賣出了第"+number--+"票,剩下"+number+"張票");
}
}
- synchronized(八鎖問題):
反映synchronized的特點:- 對于同步方法,鎖就是當前物件,
- 對于靜態同步方法,鎖是當前類的class物件
- 對于同步代碼塊,鎖是synchronized括號里配置的物件,
//1.標準情況 syn通用一把鎖
//2.加入延時 syn 鎖的物件是方法的呼叫者 ,兩個方法用的是同一把鎖,誰先拿到誰先執行
//3.增加普通方法
//4.兩個物件
//5.增加兩個靜態同步方法 靜態方法鎖的是class模板
//6.兩個物件兩個靜態方法
//7. 一個靜態同步方法 一個普通同步方法
//8. 兩個物件 一個靜態同步方法 一個普通同步方法
public class Test1 {
public static void main(String[] args) {
Phone phone = new Phone();
Phone phone1 = new Phone();
new Thread(()->{
phone.send();
}).start();
new Thread(()->{
phone1.call();
}).start();
new Thread(()->{
phone.sayHello();
}).start();
}
}
class Phone {
public static synchronized void send() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("發短信");
}
public synchronized void call() {
System.out.println("打電話");
}
public void sayHello() {
System.out.println("Hello");
}
}
5.sleep()方法和wait()方法的區別
wait()定義在Object類中,使用在同步方法中,用于執行緒通信,執行緒呼叫wait方法,會釋放掉鎖,
sleep()定義在Thread類中,是個靜態方法,用于暫停執行緒,執行緒呼叫sleep方法,不會釋放鎖
yield()定義在Thread類中,也是靜態方法,用于暫停執行緒,讓其他處于相同優先級的執行緒來競爭執行,始終處于runable狀態
join()定義在Thread類中,是個同步方法,如果在A執行緒中呼叫了B.join()方法,A執行緒會取得同步方法的鎖,如果B執行緒存活,A執行緒會呼叫wait()釋放掉鎖進入等待狀態,直到方法完成B執行緒釋放鎖會自動喚醒A執行緒,這就完成了執行緒讓步,
6.執行緒通信:
- 虛假喚醒
出現虛假喚醒問題的原因:wait()方法讓執行緒進入waiting狀態,被notify()方法喚醒后會繼續執行,如果使用if僅判斷一次,notifyAll()會讓所有之前通過if的執行緒執行,哪怕現在檢測條件已經不滿足,所以為了避免出現,需要使用while來判斷, - 等待/通知的經典范式:
- 獲取物件的鎖
- 判斷檢測,不滿足就呼叫物件的
wait()方法,被通知后仍要檢查條件, - 條件滿足則執行對應的邏輯,
//虛假喚醒問題:if / while
public class ThreadDemo1 {
public static void main(String[] args) {
Share share = new Share();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"執行緒1").start();
new Thread(()->{
for (int i = 0; i < 20; i++) {
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"執行緒2").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"執行緒3").start();
}
}
class Share{
private int number = 0;
public synchronized void incr() throws InterruptedException {
while (number != 0) {
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"執行incr,number: "+number);
this.notifyAll();
}
public synchronized void decr() throws InterruptedException {
while (number == 0) {
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+"執行decr,number: "+number);
this.notifyAll();
}
}
7.lock
- 實作多執行緒同步
public class LSaleTicket {
public static void main(String[] args) {
LTicket lTicket = new LTicket();
//lambda運算式
new Thread(()-> {
for (int i = 0; i < 30; i++) {
lTicket.sale();
}
},"執行緒1").start();
new Thread(()-> {
for (int i = 0; i < 30; i++) {
lTicket.sale();
}
},"執行緒1").start();
new Thread(()-> {
for (int i = 0; i < 30; i++) {
lTicket.sale();
}
},"執行緒1").start();
}
}
class LTicket{
private int number = 40;
public void sale () {
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
if (number > 0) {
System.out.println(Thread.currentThread().getName()+"賣出了第"+number--+"票,剩下"+number+"張票");
}
} finally {
lock.unlock();
}
}
}
- lock實作執行緒通信:
public class ThreadDemo2 {
public static void main(String[] args) {
Share share = new Share();
new Thread(()->{
for (int i = 0; i < 10; i++) {
share.incr();
}
},"執行緒A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
share.decr();
}
},"執行緒B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
share.incr();
}
},"執行緒C").start();
}
}
class Share{
private int number = 0;
private Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void incr() {
lock.lock();
try {
while (number != 0) {
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName()+"執行incr,number: "+number);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void decr() {
lock.lock();
try {
while (number != 1) {
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+"執行decr,number: "+number);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
- 實作執行緒間定制通信:通過改變標志位和等待/通知機制來實作
public class ThreadDemo3 {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(()->{
for (int i = 0; i < 10; i++) {
shareResource.print5(i);
}
},"執行緒A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
shareResource.print10(i);
}
}, "執行緒B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
shareResource.print15(i);
}
}, "執行緒C").start();
}
}
class ShareResource{
private int flag = 1;
private Lock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition();
public void print5(long loop) {
lock.lock();
try{
while (flag != 1) {
conditionA.await();
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"列印"+i+"輪次"+loop);
}
//改變標志位
flag = 2;
//喚醒其它執行緒
conditionB.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print10(long loop) {
lock.lock();
try{
while (flag != 2) {
conditionB.await();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"列印"+i+"輪次"+loop);
}
//改變標志位
flag = 3;
//喚醒其它執行緒
conditionC.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print15(long loop) {
lock.lock();
try{
while (flag != 3) {
conditionC.await();
}
for (int i = 0; i < 15; i++) {
System.out.println(Thread.currentThread().getName()+"列印"+i+"輪次"+loop);
}
//改變標志位
flag = 1;
//喚醒其它執行緒
conditionA.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
8、執行緒不安全的集合類
- List
類ArrayList是執行緒不安全的,多個執行緒呼叫put()方法時,會拋出例外,
常用的解決方法是寫時復制機制,添加集合元素時,先復制一個副本,在副本上添加元素,再讓變數指標指向副本,這個程序需要持有lock鎖,完成后再釋放鎖,
//解決list不安全
//1.List<Integer> list = new Vector<>();
//2.List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
//3.List<Integer> list = new CopyOnWriteArrayList<>();
public class ListTest {
public static void main(String[] args) {
List<Integer> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 100; i++) {
int temp = i;
new Thread(()-> {
list.add(temp);
System.out.println(Thread.currentThread().getName()+list);
}, String.valueOf(i)).start();
}
}
}
- Set
//set不安全
//1.Set<Integer> set = Collections.synchronizedSet(new HashSet<>());
//2.Set<Integer> set = new CopyOnWriteArraySet<>();
public class SetTest {
public static void main(String[] args) {
Set<Integer> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 100; i++) {
int temp = i;
new Thread(()->{
set.add(temp);
System.out.println(Thread.currentThread().getName()+set);
},String.valueOf(i)).start();
}
}
}
- Map
//map不安全
//1.Map<Integer,String> map = Collections.synchronizedMap(new HashMap<>());
//2.Map<Integer,String> map = new ConcurrentHashMap<>();
public class MapTest {
public static void main(String[] args) {
Map<Integer,String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 100; i++) {
int temp = i;
new Thread(()->{
map.put(temp,"hello");
System.out.println(Thread.currentThread().getName()+map);
},String.valueOf(i)).start();
}
}
}
9.死鎖問題
出現原因
- 競爭資源
- 持有資源不釋放
public class DeadLock {
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
new Thread(()->{
synchronized (a) {
System.out.println(Thread.currentThread().getName()+"持有鎖a,想獲取鎖b");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b) {
System.out.println("獲取到了鎖b");
}
}
},"執行緒A").start();
new Thread(()->{
synchronized (b) {
System.out.println(Thread.currentThread().getName()+"持有鎖b,想獲取鎖a");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a) {
System.out.println("獲取到了鎖a");
}
}
},"執行緒B").start();
}
}
10. 并發工具類
簡單的記錄一下怎么使用,
- CountDownLatch
讓一個執行緒或多個執行緒等待其它執行緒完成作業,如果其它執行緒沒有完成作業,當前執行緒會一直處于阻塞狀態,其它執行緒都完成作業后,才執行await()后面的程式,
public class CountDownLatch {
public static void main(String[] args) throws InterruptedException {
java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" 同學離開了!");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("班長鎖門了!");
}
}
- 同步屏障CyclicBarrier
每一個執行緒到達一個屏障時被阻塞,直到最后一個執行緒到達屏障,屏障才會打開,所有被屏障攔截的執行緒才會繼續執行,每個執行緒呼叫await()方法時表明已經到達屏障,然后當前執行緒被阻塞,
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("集齊七龍珠召喚神龍!");
});
for (int i = 0; i < 7; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" 收集到龍珠!");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
- 信號燈 SemaPhore
控制同時訪問特定資源的執行緒數量,
release()會動態的增加許可數量,構造器引數只是說明了一個許可證的初始值,
public class SemaPhoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"搶到了車位!");
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
System.out.println(Thread.currentThread().getName()+"離開了!");
}
},String.valueOf(i)).start();
}
}
}
11、讀寫鎖
- 讀寫鎖的區別
其他鎖基本是排他鎖,同一時刻只允許一個執行緒訪問,讀寫鎖維護類一對鎖,一個讀鎖,一個寫鎖,在同一時刻可以允許多個讀執行緒訪問,在寫執行緒訪問時,所有的讀執行緒和其它寫執行緒被阻塞 - 鎖獲取
寫鎖獲取:如果存在讀鎖,則不能獲取,并且寫鎖是排他鎖,只能由一個執行緒持有,如果允許讀鎖在已經獲取的情況下獲取寫鎖,那么持有讀鎖的執行緒時感覺不到寫鎖執行緒的操作的,
讀鎖獲取:只有在當前執行緒獲取寫鎖或者沒有任何一個執行緒獲得寫鎖的情況下,才能獲取讀鎖, - 鎖降級
程序:當前執行緒獲得寫鎖,再獲取讀鎖,最后釋放寫鎖,
為什么不支持鎖升級?可能有多個執行緒獲取了讀鎖,在獲取寫鎖,其它持有讀鎖的執行緒感覺不到寫鎖執行緒的操作,
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCache = new MyCache();
//寫操作
for (int i = 0; i < 5; i++) {
final int num = i;
new Thread(()->{
myCache.put(num+"",num+"");
},String.valueOf(i)).start();
}
//讀操作
for (int i = 0; i < 5; i++) {
final int num = i;
new Thread(()->{
myCache.get(num+"");
},String.valueOf(i)).start();
}
}
}
class MyCache{
private volatile Map<Object,Object> map = new HashMap<>();
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(Object k,Object v) {
//寫鎖
readWriteLock.writeLock().lock();
System.out.println(Thread.currentThread().getName()+" 正在寫");
try {
TimeUnit.SECONDS.sleep(3);
map.put(k,v);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
readWriteLock.writeLock().unlock();
}
System.out.println(Thread.currentThread().getName()+" 寫完了!");
}
public Object get(Object k) {
//讀鎖
readWriteLock.readLock().lock();
System.out.println(Thread.currentThread().getName()+" 正在讀");
Object value = https://www.cnblogs.com/echoxiatiandefeng/archive/2021/09/25/null;
try {
TimeUnit.SECONDS.sleep(3);
value = map.get(k);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
readWriteLock.readLock().unlock();
}
System.out.println(Thread.currentThread().getName()+" 讀完了!");
return value;
}
}
12.阻塞佇列
- 定義:支持兩個阻塞操作的佇列
阻塞的插入方法:當佇列滿的的時候,佇列會阻塞插入元素的執行緒,直到佇列不滿的時候
阻塞的移除方法:在佇列為空的時候,佇列會阻塞獲取元素的執行緒,等待佇列變為非空, - 常見的阻塞佇列:無界的阻塞佇列默認的長度是Integer.MAX_VALUE
ArrayBlockingQueue 有界阻塞佇列; LinkedBlockingQueue 無界阻塞佇列; DelayQueue 優先級佇列實作的無界阻塞佇列, - 4中處理方式
//阻塞佇列
public class BlockQueueDemo {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<Integer>(3);
// 第一組方法
System.out.println(blockingQueue.add(1));
System.out.println(blockingQueue.add(2));
System.out.println(blockingQueue.add(3));
System.out.println(blockingQueue.add(4));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
// 第二組方法
System.out.println(blockingQueue.offer(1));
System.out.println(blockingQueue.offer(2));
System.out.println(blockingQueue.offer(3));
System.out.println(blockingQueue.offer(4));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
// 第三組方法
blockingQueue.put(1);
blockingQueue.put(1);
blockingQueue.put(1);
blockingQueue.put(1);
blockingQueue.take();
blockingQueue.take();
blockingQueue.take();
blockingQueue.take();
//第四組方法
blockingQueue.offer(1,3, TimeUnit.SECONDS);
blockingQueue.offer(1,3, TimeUnit.SECONDS);
blockingQueue.offer(1,3, TimeUnit.SECONDS);
blockingQueue.offer(1,4, TimeUnit.SECONDS);
blockingQueue.poll(4,TimeUnit.SECONDS);
blockingQueue.poll(4,TimeUnit.SECONDS);
blockingQueue.poll(4,TimeUnit.SECONDS);
blockingQueue.poll(2,TimeUnit.SECONDS);
System.out.println(blockingQueue);
}
}
13.執行緒池
有三種常見的執行緒池:FixedThreadPool、SingleThreadExecutor、CachedThreadPool
- 執行緒池的核心引數:
corePoolSize:核心執行緒數
maximumPoolSize:執行緒池最大數量
runnableTaskQueue:任務阻塞佇列
keepAliveTime:執行緒活動保持時間
TimeUnit: 執行緒活動保持時間的單位
RejectedExcecutionHandler:飽和拒絕策略 - 執行緒池作業流程
執行execute(),判斷核心執行緒池滿沒滿(是否都在執行任務),沒滿就創建一個作業執行緒;滿了就下一步判斷阻塞佇列滿沒滿,沒滿就把任務存在佇列里,滿了就下一步判斷執行緒池最大執行緒,沒滿就創建一個新的作業執行緒,滿了就下一步執行拒絕策略,
核心執行緒池->作業佇列->執行緒池最大執行緒->拒絕策略 - 自定義執行緒池:經常使用到
public class ThreadPollDemo2 {
public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(3, 5, 2L, TimeUnit.MICROSECONDS,
new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 10; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"辦理業務");
});
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/302915.html
標籤:其他
上一篇:JAVA多執行緒
