14. 秋天の第一篇并發(fā)編程總結(jié)

朋友圈莫名的流傳起“秋天的第一杯奶茶”

(反正就是要紅包唄, 切)

開始大概就是這樣的

image

慢慢的變成了這樣的

image

最后畫風(fēng)變得越來越奇怪……

image
image

所以, 我也得跟個風(fēng)

image

前言

這個專欄也寫了好幾篇文章了, 常用的知識點(diǎn),并發(fā)編程的技巧也寫的差不多了,本章就來對之前的知識進(jìn)行個總結(jié).

通過學(xué)習(xí),我們知道

并發(fā)的本質(zhì)就是多線程對同一資源的占用問題.

解決并發(fā)問題的根本就是讓線程間進(jìn)行正確的通信.

其中兩個關(guān)鍵點(diǎn)如下:

  1. 線程通信:重點(diǎn)關(guān)注線程同步的幾種方式

  2. 正確通信:重點(diǎn)關(guān)注是否有線程安全問題

Java中提供了很多線程同步操作,比如:

  • synchronized關(guān)鍵字
  • wait/notifyAll
  • ReentrantLock
  • Condition

并發(fā)包下的工具類:

  • Semaphore
  • ThreadLocal
  • AbstractQueuedSynchronizer
  • ……

接下來主要說明一下這幾種同步方式的使用及優(yōu)劣.

ReentrantLock可重入鎖

JDK5開始, 新增了Lock接口以及它的一個實(shí)現(xiàn)類ReentrantLock.
ReentrantLock可重入鎖是J.U.C包(java.util.concurrent)內(nèi)置的一個鎖對象,可以用來實(shí)現(xiàn)同步,

基本使用方法如下:

public class ReentrantLockTest {
    private ReentrantLock lock = new ReentrantLock();
    public void execute() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " do something synchronize");
            try {
                Thread.sleep(5000l);
            } catch (InterruptedException e) {
                System.err.println(Thread.currentThread().getName() + " interrupted");
                Thread.currentThread().interrupt();
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockTest reentrantLockTest = new ReentrantLockTest();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLockTest.execute();
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLockTest.execute();
            }
        });
        thread1.start();
        thread2.start();
    }
}

上面例子表示 同一時(shí)間段只能有1個線程執(zhí)行execute方法,輸出如下:

Thread-0 do something synchronize
// 隔了5秒鐘
Thread-1 do something synchronize

可重入鎖中可重入表示的意義在于

對于同一個線程,可以繼續(xù)調(diào)用加鎖的方法,而不會被掛起.
可重入鎖內(nèi)部維護(hù)一個計(jì)數(shù)器,對于同一個線程調(diào)用lock方法,計(jì)數(shù)器+1,調(diào)用unlock方法,計(jì)數(shù)器-1.

舉個例子再次說明一下可重入的意思:

在一個加鎖方法execute中調(diào)用另外一個加鎖方法anotherLock并不會被掛起,可以直接調(diào)用(調(diào)用execute方法時(shí)計(jì)數(shù)器+1,然后內(nèi)部又調(diào)用了anotherLock方法,計(jì)數(shù)器+1,變成了2):

public void execute() {
    lock.lock();
    try {
        System.out.println(Thread.currentThread().getName() + " do something synchronize");
        try {
            anotherLock();
            Thread.sleep(5000l);
        } catch (InterruptedException e) {
            System.err.println(Thread.currentThread().getName() + " interrupted");
            Thread.currentThread().interrupt();
        }
    } finally {
        lock.unlock();
    }
}

public void anotherLock() {
    lock.lock();
    try {
        System.out.println(Thread.currentThread().getName() + " invoke anotherLock");
    } finally {
        lock.unlock();
    }
}

輸出:

Thread-0 do something synchronize
Thread-0 invoke anotherLock
// 隔了5秒鐘
Thread-1 do something synchronize
Thread-1 invoke anotherLock

synchronized

synchronized跟ReentrantLock一樣,也支持可重入鎖.
但是它是一個關(guān)鍵字, 是一種語法級別的同步方式, 稱為內(nèi)置鎖.

public class SynchronizedKeyWordTest {
    public synchronized void execute() {
            System.out.println(Thread.currentThread().getName() + " do something synchronize");
        try {
            anotherLock();
            Thread.sleep(5000l);
        } catch (InterruptedException e) {
            System.err.println(Thread.currentThread().getName() + " interrupted");
            Thread.currentThread().interrupt();
        }
    }

    public synchronized void anotherLock() {
        System.out.println(Thread.currentThread().getName() + " invoke anotherLock");
    }

    public static void main(String[] args) {
        SynchronizedKeyWordTest reentrantLockTest = new SynchronizedKeyWordTest();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLockTest.execute();
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLockTest.execute();
            }
        });
        thread1.start();
        thread2.start();
    }
}

輸出結(jié)果跟ReentrantLock一樣,這個例子說明內(nèi)置鎖可以作用在方法上.
synchronized關(guān)鍵字也可以修飾靜態(tài)方法,此時(shí)如果調(diào)用該靜態(tài)方法,將會鎖住整個類.

同步是一種高開銷的操作,因此應(yīng)該盡量減少同步的內(nèi)容.通常沒有必要同步整個方法,使用synchronized代碼塊同步關(guān)鍵代碼即可.

synchronized跟ReentrantLock相比,有幾點(diǎn)局限性:

  1. 加鎖的時(shí)候不能設(shè)置超時(shí).
    ReentrantLock有提供tryLock方法,可以設(shè)置超時(shí)時(shí)間,如果超過了這個時(shí)間并且 沒有獲取到鎖,就會放棄,而synchronized卻沒有這種功能;
  2. ReentrantLock可以使用多個Condition,而synchronized卻只能有1個
  3. 不能中斷一個試圖獲得鎖的線程;
  4. ReentrantLock可以選擇公平鎖和非公平鎖;
  5. ReentrantLock可以獲得正在等待線程的個數(shù),計(jì)數(shù)器等

所以, Lock的操作與synchronized相比,靈活性更高,而且Lock提供多種方式獲取鎖,有Lock、ReadWriteLock接口,以及實(shí)現(xiàn)這兩個接口的ReentrantLock類、ReentrantReadWriteLock類.

關(guān)于Lock對象和synchronized關(guān)鍵字選擇的考量:

  1. 最好兩個都不用,使用一種java.util.concurrent包提供的機(jī)制,能夠幫助用戶處理所有與鎖相關(guān)的代碼.
  2. 如果synchronized關(guān)鍵字能滿足用戶的需求,就用synchronized,因?yàn)樗芎喕a.
  3. 如果需要更高級的功能,就用ReentrantLock類,此時(shí)要注意及時(shí)釋放鎖,否則會出現(xiàn)死鎖,通常在finally代碼釋放鎖.

在性能考量上來說,如果競爭資源不激烈,兩者的性能是差不多的,而當(dāng)競爭資源非常激烈時(shí)(即有大量線程同時(shí)競爭),此時(shí)Lock的性能要遠(yuǎn)遠(yuǎn)優(yōu)于synchronized.所以說,在具體使用時(shí)要根據(jù)適當(dāng)情況選擇.

Condition條件對象

Condition條件對象的意義在于 對于一個已經(jīng)獲取Lock鎖的線程,如果還需要等待其他條件才能繼續(xù)執(zhí)行的情況下,才會使用Condition條件對象.

Condition可以替代傳統(tǒng)的線程間通信, 用await()替換wait(), 用signal()替換notify(),用signalAll()替換notifyAll().

為什么方法名不直接叫wait()/notify()/nofityAll()?因?yàn)镺bject的這幾個方法是final的,不可重寫!

public class ConditionTest {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " run");
                    System.out.println(Thread.currentThread().getName() + " wait for condition");
                    try {
                        condition.await();
                        System.out.println(Thread.currentThread().getName() + " continue");
                    } catch (InterruptedException e) {
                        System.err.println(Thread.currentThread().getName() + " interrupted");
                        Thread.currentThread().interrupt();
                    }
                } finally {
                    lock.unlock();
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " run");
                    System.out.println(Thread.currentThread().getName() + " sleep 5 secs");
                    try {
                        Thread.sleep(5000l);
                    } catch (InterruptedException e) {
                        System.err.println(Thread.currentThread().getName() + " interrupted");
                        Thread.currentThread().interrupt();
                    }
                    condition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}

這個例子中thread1執(zhí)行到condition.await()時(shí),當(dāng)前線程會被掛起;
直到thread2調(diào)用了condition.signalAll()方法之后,thread1才會重新被激活執(zhí)行.

這里需要注意的是thread1調(diào)用Condition的await方法之后,thread1線程釋放鎖,然后馬上加入到Condition的等待隊(duì)列,由于thread1釋放了鎖,thread2獲得鎖并執(zhí)行,thread2執(zhí)行signalAll方法之后,Condition中的等待隊(duì)列thread1被取出并加入到AQS中,接下來thread2執(zhí)行完畢之后釋放鎖,由于thread1已經(jīng)在AQS的等待隊(duì)列中,所以thread1被喚醒,繼續(xù)執(zhí)行.

傳統(tǒng)線程的通信方式,Condition都可以實(shí)現(xiàn).
Condition的強(qiáng)大之處在于它可以為多個線程間建立不同的Condition.

注意,Condition是被綁定到Lock上的,要創(chuàng)建一個Lock的Condition必須用newCondition()方法.

wait&notify/notifyAll方式

Java線程的狀態(tài)轉(zhuǎn)換圖與相關(guān)方法,如下:


線程狀態(tài)轉(zhuǎn)換圖

在圖中,紅框標(biāo)識的部分方法,可以認(rèn)為已過時(shí),不再使用.
上圖中的方法能夠參與到線程同步中的方法,如下:

  1. wait、notify、notifyAll方法:
    線程中通信可以使用的方法.
    線程中調(diào)用了wait方法,則進(jìn)入阻塞狀態(tài),只有等另一個線程調(diào)用與wait同一個對象的notify方法.
    這里有個特殊的地方,調(diào)用wait或者notify,前提是需要獲取鎖,也就是說,需要在同步塊中做以上操作.

wait/notifyAll方式跟ReentrantLock/Condition方式的原理是一樣的.

Java中每個對象都擁有一個內(nèi)置鎖,在內(nèi)置鎖中調(diào)用wait,notify方法相當(dāng)于調(diào)用鎖的Condition條件對象的await和signalAll方法.

public class WaitNotifyAllTest {

    public synchronized void doWait() {
        System.out.println(Thread.currentThread().getName() + " run");
        System.out.println(Thread.currentThread().getName() + " wait for condition");
        try {
            this.wait();
            System.out.println(Thread.currentThread().getName() + " continue");
        } catch (InterruptedException e) {
            System.err.println(Thread.currentThread().getName() + " interrupted");
            Thread.currentThread().interrupt();
        }
    }

    public synchronized void doNotify() {
        try {
            System.out.println(Thread.currentThread().getName() + " run");
            System.out.println(Thread.currentThread().getName() + " sleep 5 secs");
            Thread.sleep(5000l);
            this.notifyAll();
        } catch (InterruptedException e) {
            System.err.println(Thread.currentThread().getName() + " interrupted");
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        WaitNotifyAllTest waitNotifyAllTest = new WaitNotifyAllTest();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                waitNotifyAllTest.doWait();
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                waitNotifyAllTest.doNotify();
            }
        });
        thread1.start();
        thread2.start();
    }
}

這里需要注意的是 調(diào)用wait/notifyAll方法的時(shí)候一定要獲得當(dāng)前線程的鎖,否則會發(fā)生IllegalMonitorStateException異常.

  1. join方法:該方法主要作用是在該線程中的run方法結(jié)束后,才往下執(zhí)行.
package com.thread.simple;
 
public class ThreadJoin {
    public static void main(String[] args) {
        Thread thread= new Thread(new Runnable() {
              @Override
              public void run() {
                   System.err.println("線程"+Thread.currentThread().getId()+" 打印信息");
              }
        });
        thread.start();
     
        try {
            thread.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.err.println("主線程打印信息");   
    }
}
  1. yield方法:線程本身的調(diào)度方法,使用時(shí)線程可以在run方法執(zhí)行完畢時(shí),調(diào)用該方法,告知線程已可以出讓CPU資源.
public class Test1 {  
    public static void main(String[] args) throws InterruptedException {  
        new MyThread("低級", 1).start();  
        new MyThread("中級", 5).start();  
        new MyThread("高級", 10).start();  
    }  
}  

class MyThread extends Thread {  
    public MyThread(String name, int pro) {  
        super(name);// 設(shè)置線程的名稱  
        this.setPriority(pro);// 設(shè)置優(yōu)先級  
    }  

    @Override  
    public void run() {  
        for (int i = 0; i < 30; i++) {  
            System.out.println(this.getName() + "線程第" + i + "次執(zhí)行!");  
            if (i % 5 == 0)  
                Thread.yield();  
        }  
    }  
}  
  1. sleep方法:通過sleep(millis)使線程進(jìn)入休眠一段時(shí)間,該方法在指定的時(shí)間內(nèi)無法被喚醒,同時(shí)也不會釋放對象鎖;
/**
 * 可以明顯看到打印的數(shù)字在時(shí)間上有些許的間隔
 */
public class Test1 {  
    public static void main(String[] args) throws InterruptedException {  
        for(int i=0;i<100;i++){  
            System.out.println("main"+i);  
            Thread.sleep(100);  
        }  
    }  
} 

sleep方法告訴操作系統(tǒng) 至少在指定時(shí)間內(nèi)不需為線程調(diào)度器為該線程分配執(zhí)行時(shí)間片,并不釋放鎖(如果當(dāng)前已經(jīng)持有鎖).實(shí)際上,調(diào)用sleep方法時(shí)并不要求持有任何鎖.

所以,sleep方法并不需要持有任何形式的鎖,也就不需要包裹在synchronized中.

ThreadLocal

ThreadLocal類可以理解為線程本地變量.

也就是說如果定義了一個ThreadLocal, 每個線程往這個ThreadLocal中讀寫是線程隔離, 互相之間不會影響的.

它提供了一種將可變數(shù)據(jù)通過每個線程有自己的獨(dú)立副本從而實(shí)現(xiàn)線程封閉的機(jī)制.

PS: ThreadLocal的數(shù)據(jù)線程隔離這點(diǎn)一定要注意!

假設(shè)有一個共享變量ticket初始值為 0
線程A設(shè)置ticket為 1, 放入了ThreadLocal;
線程B設(shè)置ticket為 2, 放入了ThreadLocal;
假設(shè)A、B線程同時(shí)執(zhí)行, 此時(shí)若get(), 那么A始終是1, B始終是2;
并不存在ticket值覆蓋的情況, 因?yàn)锳、B操作的都是一個獨(dú)立的副本!

比如:SimpleDateFormat不是一個線程安全的類,可以使用ThreadLocal實(shí)現(xiàn)同步,如下:

public class ThreadLocalTest {

    private static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Date date = new Date();
                System.out.println(dateFormatThreadLocal.get().format(date));
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Date date = new Date();
                System.out.println(dateFormatThreadLocal.get().format(date));
            }
        });
        thread1.start();
        thread2.start();
    }
}

為何SimpleDateFormat不是線程安全的類?具體請參考:

  1. https://blog.csdn.net/zdp072/article/details/41044059
  2. https://blog.csdn.net/zq602316498/article/details/40263083

PS: 現(xiàn)在Java8提供了DateTimeFormatter它是線程安全的.

ThreadLocal與同步機(jī)制的對比選擇:

  1. ThreadLocal與同步機(jī)制都是 為了解決多線程中相同變量的訪問沖突問題.
  2. 前者采用以 "空間換時(shí)間" 的方法,后者采用以 "時(shí)間換空間" 的方式.

volatile修飾變量

volatile關(guān)鍵字為域變量的訪問提供了一種免鎖機(jī)制,使用volatile修飾域相當(dāng)于告訴虛擬機(jī)該域可能會被其他線程更新,因此每次使用該域就要重新計(jì)算,而不是使用寄存器中的值,volatile不會提供任何原子操作,它也不能用來修飾final類型的變量.

//只給出要修改的代碼,其余代碼與上同
public class Bank {
    //需要同步的變量加上volatile
    private volatile int account = 100;
    public int getAccount() {
        return account;
    }
    //這里不再需要synchronized 
    public void save(int money) {
        account += money;
    }
}

多線程中的非同步問題主要出現(xiàn)在對域的讀寫上,如果讓域自身避免這個問題,則就不需要修改操作該域的方法.用final域,有鎖保護(hù)的域和volatile域可以避免非同步的問題.

Semaphore信號量

Semaphore信號量被用于控制特定資源在同一個時(shí)間被訪問的個數(shù).類似連接池的概念,保證資源可以被合理的使用.可以使用構(gòu)造器初始化資源個數(shù):

public class SemaphoreTest {

    private static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        for(int i = 0; i < 5; i ++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + "上廁所");
                        Thread.sleep(5000l);
                        semaphore.release();
                        System.out.println(Thread.currentThread().getName() + "讓出坑位");
                    } catch (InterruptedException e) {
                        System.err.println(Thread.currentThread().getName() + " interrupted");
                    }
                }
            }).start();
        }
    }
}

輸出:

Thread-0上廁所
Thread-1上廁所
Thread-0讓出坑位
Thread-2上廁所
Thread-1讓出坑位
Thread-3上廁所
Thread-2讓出坑位
Thread-4上廁所
Thread-3讓出坑位
Thread-4讓出坑位

并發(fā)包下的工具類

CountDownLatch

CountDownLatch是一個計(jì)數(shù)器,它的構(gòu)造方法中需要設(shè)置一個數(shù)值,用來設(shè)定計(jì)數(shù)的次數(shù).每次調(diào)用countDown()方法之后,這個計(jì)數(shù)器都會減去1,CountDownLatch會一直阻塞著調(diào)用await()方法的線程,直到計(jì)數(shù)器的值變?yōu)?.

public class CountDownLatchTest {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for(int i = 0; i < 5; i ++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " " + new Date() + " run");
                    try {
                        Thread.sleep(5000l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    countDownLatch.countDown();
                }
            }).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("all thread over");
    }
}

輸出:

Thread-2 Mon Apr 18 18:18:30 CST 2016 run
Thread-3 Mon Apr 18 18:18:30 CST 2016 run
Thread-4 Mon Apr 18 18:18:30 CST 2016 run
Thread-0 Mon Apr 18 18:18:30 CST 2016 run
Thread-1 Mon Apr 18 18:18:30 CST 2016 run
all thread over

CyclicBarrier

CyclicBarrier阻塞調(diào)用的線程,直到條件滿足時(shí),阻塞的線程同時(shí)被打開.

調(diào)用await()方法的時(shí)候,這個線程就會被阻塞,當(dāng)調(diào)用await()的線程數(shù)量到達(dá)屏障數(shù)的時(shí)候,主線程就會取消所有被阻塞線程的狀態(tài).

在CyclicBarrier的構(gòu)造方法中,還可以設(shè)置一個barrierAction.在所有的屏障都到達(dá)之后,會啟動一個線程來運(yùn)行這里面的代碼.

public class CyclicBarrierTest {

    public static void main(String[] args) {
        Random random = new Random();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for(int i = 0; i < 5; i ++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int secs = random.nextInt(5);
                    System.out.println(Thread.currentThread().getName() + " " + new Date() + " run, sleep " + secs + " secs");
                    try {
                        Thread.sleep(secs * 1000);
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " " + new Date() + " runs over");
                }
            }).start();
        }
    }
}

相比CountDownLatch,CyclicBarrier是可以被循環(huán)使用的,而且遇到線程中斷等情況時(shí),還可以利用reset()方法,重置計(jì)數(shù)器,從這些方面來說,CyclicBarrier會比CountDownLatch更加靈活一些.

使用原子變量實(shí)現(xiàn)線程同步

有時(shí)需要使用線程同步的根本原因在于 "對普通變量的操作不是原子的".
那么什么是原子操作呢?

原子操作就是指將讀取變量值、修改變量值、保存變量值看成一個整體來操作
即-這幾種行為要么同時(shí)完成,要么都不完成.

在java.util.concurrent.atomic包中提供了創(chuàng)建原子類型變量的工具類,使用該類可以簡化線程同步.比如:其中AtomicInteger以原子方式更新int的值:

class Bank {
    private AtomicInteger account = new AtomicInteger(100);

    public AtomicInteger getAccount() {
        return account;
    }

    public void save(int money) {
        account.addAndGet(money);
    }
}

AbstractQueuedSynchronizer

AQS是很多同步工具類的基礎(chǔ),
比如:ReentrantLock里的公平鎖和非公平鎖,Semaphore里的公平鎖和非公平鎖,
CountDownLatch里的鎖等他們的底層都是使用AbstractQueuedSynchronizer完成的.

基于AbstractQueuedSynchronizer自定義實(shí)現(xiàn)一個獨(dú)占鎖:

public class MySynchronizer extends AbstractQueuedSynchronizer {

    @Override
    protected boolean tryAcquire(int arg) {
        if(compareAndSetState(0, 1)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int arg) {
        setState(0);
        setExclusiveOwnerThread(null);
        return true;
    }

    public void lock() {
        acquire(1);
    }

    public void unlock() {
        release(1);
    }

    public static void main(String[] args) {
        MySynchronizer mySynchronizer = new MySynchronizer();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                mySynchronizer.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " run");
                    System.out.println(Thread.currentThread().getName() + " will sleep 5 secs");
                    try {
                        Thread.sleep(5000l);
                        System.out.println(Thread.currentThread().getName() + " continue");
                    } catch (InterruptedException e) {
                        System.err.println(Thread.currentThread().getName() + " interrupted");
                        Thread.currentThread().interrupt();
                    }
                } finally {
                    mySynchronizer.unlock();
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                mySynchronizer.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " run");
                } finally {
                    mySynchronizer.unlock();
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}

使用阻塞隊(duì)列實(shí)現(xiàn)線程同步

前面幾種同步方式都是基于底層實(shí)現(xiàn)的線程同步,但是在實(shí)際開發(fā)當(dāng)中,應(yīng)當(dāng)盡量遠(yuǎn)離底層結(jié)構(gòu).本節(jié)主要是使用LinkedBlockingQueue<E>來實(shí)現(xiàn)線程的同步.

LinkedBlockingQueue<E>是一個基于鏈表的隊(duì)列,先進(jìn)先出的順序(FIFO),范圍任意的blocking queue.

package com.xhj.thread;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 用阻塞隊(duì)列實(shí)現(xiàn)線程同步 LinkedBlockingQueue的使用
 */
public class BlockingSynchronizedThread {
    /**
     * 定義一個阻塞隊(duì)列用來存儲生產(chǎn)出來的商品
     */
    private LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
    /**
     * 定義生產(chǎn)商品個數(shù)
     */
    private static final int size = 10;
    /**
     * 定義啟動線程的標(biāo)志,為0時(shí),啟動生產(chǎn)商品的線程;為1時(shí),啟動消費(fèi)商品的線程
     */
    private int flag = 0;

    private class LinkBlockThread implements Runnable {
        @Override
        public void run() {
            int new_flag = flag++;
            System.out.println("啟動線程 " + new_flag);
            if (new_flag == 0) {
                for (int i = 0; i < size; i++) {
                    int b = new Random().nextInt(255);
                    System.out.println("生產(chǎn)商品:" + b + "號");
                    try {
                        queue.put(b);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("倉庫中還有商品:" + queue.size() + "個");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else {
                for (int i = 0; i < size / 2; i++) {
                    try {
                        int n = queue.take();
                        System.out.println("消費(fèi)者買去了" + n + "號商品");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("倉庫中還有商品:" + queue.size() + "個");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        BlockingSynchronizedThread bst = new BlockingSynchronizedThread();
        LinkBlockThread lbt = bst.new LinkBlockThread();
        Thread thread1 = new Thread(lbt);
        Thread thread2 = new Thread(lbt);
        thread1.start();
        thread2.start();
    }
}

補(bǔ)充-公平/非公平鎖

ReentranLock分為公平鎖和非公平鎖,

二者的區(qū)別就在獲取鎖機(jī)會是否和排隊(duì)順序相關(guān);

我們都知道, 如果鎖被另一個線程持有, 那么申請鎖的其他線程會被掛起等待,加入等待隊(duì)列;

理論上, 先調(diào)用lock函數(shù)被掛起等待的線程應(yīng)該排在等待隊(duì)列的前端,后調(diào)用的就排在后邊;

如果此時(shí)鎖被釋放, 需要通知等待線程再次嘗試獲取鎖;

公平鎖會讓最先進(jìn)入隊(duì)列的線程獲得鎖;

而非公平鎖則會喚醒所有線程, 讓它們再次嘗試獲取鎖, 所以可能會導(dǎo)致后來的線程先獲得了鎖, 則就是非公平.

Synchronized是非公平鎖, ReentranLock默認(rèn)的lock方法采用的是非公平鎖.

訂閱號.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容