Java Thread Overview

線程的創建#

創建線程有兩種方式:繼承Thread類,或者實現Runnable接口

繼承Thread類##

public class MyThread extends Thread{
    public void run(){
        System.out.println("MyThread running");
    }
}

MyThread myThread = new MyThread();
myThread.start();

也可以創建一個匿名類繼承自Thread

Thread thread = new Thread(){
    public void run(){
        System.out.println("Thread running");
    }
}

thread.start();

實現Runnable接口##

public class MyRunnable implements Runnable{
    public void run(){
        System.out.println("MyRunnable running");
    }
}

Thread myThread = new Thread(new MyRunnable());
myThread.start();

常見錯誤:start()而不是run()##

不管實現Runnable接口還是繼承自Thread類,通過start方法去啟動該線程。如果調用的是run方法,其實是在當前線程執行的。
這可以通過下面的例子驗證


public class MyThread extends Thread{

    public void run(){
        System.out.println(Thread.currentThread() + ": running 1");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() + ": running 2");
    }
    
    public static void main(String[] args) throws InterruptedException {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        thread1.run();
        thread2.run();
        thread1.join();
        thread2.join();
    }
}

輸出結果是

Thread[main,5,main]: running 1
Thread[main,5,main]: running 2
Thread[main,5,main]: running 1
Thread[main,5,main]: running 2

而如果把run改為start,輸出結果才符合我們的預期

Thread[Thread-0,5,main]: running 1
Thread[Thread-1,5,main]: running 1
Thread[Thread-0,5,main]: running 2
Thread[Thread-1,5,main]: running 2

線程安全#

下圖描述了java內存模型


java-memory-model.png

多線程之間可能會共享變量。當他們同時修改一個共享變量時,就會產生race condition。這時候,可以使用synchronized關鍵字或者Lock避免race condition。

synchronized##

a synchronized block guarantees that only one thread can enter a given critial section. synchronized block also guarantee that all the variables accessed inside the synchronized block will be read in from main memory, and when the thread exists synchronized block, all update variables will be flushed back to main memory again.

synchronized關鍵字可以用來標記四中不同的block。

  • instance method
  • static method
  • code blocks inside instance method
  • code blocks inside static method
  public class MyClass {
  
    public synchronized void log1(String msg1, String msg2){
       log.writeln(msg1);
       log.writeln(msg2);
    }

  
    public void log2(String msg1, String msg2){
       synchronized(this){
          log.writeln(msg1);
          log.writeln(msg2);
       }
    }
  }

Lock##

Lock其實是用synchronized關鍵字實現的。下面是一個簡單的實現

public class Lock{
    private boolean isLocked = false;

    public synchronized void lock()
        throws InterruptedException{
        while(isLocked){
          wait();
        }
        isLocked = true;
    }

    public synchronized void unlock(){
        isLocked = false;
        notify();
    }
}

java.util.concurrent.Lock包中,Lock是一個接口,有以下幾個方法

  • lock()
  • lockInterruptibly()
  • trylock()
  • trylock(long timeout, TimeUnit timeUnit)
  • unlock()

實現Lock接口的類有ReentrantLock和ReadWriteLock。
ReentrantLock就是普通的lock。
ReadWriteLock實現了多讀,單寫。

ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

readWriteLock.readLock().lock();
// multiple readers can enter this section
// if not locked for writing, and not writers waiting
// to lock for writing.
readWriteLock.readLock().unlock();

readWriteLock.writeLock().lock();
// only one writer can enter this section,
// and only if no threads are currently reading.
readWriteLock.writeLock().unlock()

synchronized和Lock##

synchronized和Lock還是有些區別的:

  • 如果有多個線程等待,synchronized block不保證這些線程進入的順序就是他們到達等待的順序
  • 因為不能傳遞參數給synchronized block,因此沒法設置timeout時間
  • synchronized block必須在一個函數體內。但是lock和unlock可以在不同的函數體內。

線程安全的容器##

java.util.concurrent包里面提供了很多線程安全的容器,可以讓我們在多線程編程的時候更加容易。

  • BlockingQueue
  • ArrayBlockingQueue
  • LinkedBlockingQueue
  • DelayQueue
  • PriorityBlockingQueue
  • SynchronousQueue
  • BlockingDeque
  • LinkedBlockingDeque
  • ConcurrentMap
  • ConcurrentNavigableMap

線程安全的類##

多線程使得任何操作都變得如履薄冰。比如,你想對一個int類型的共享變量進行++操作,那么傳統的 i++不是線程安全的。因為這句并不是原子操作。因為java給我們提供了一些原子操作類。

  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
  • AtomicReference
  • AtomicStampedReference
  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicReferenceArray

線程同步#

wait & notify##

java.lang.Object定義了三個方法 wait(), notify(), notifyAll()。通過這幾個方法,可以讓一個線程等待一個信號,也可以讓另外一個線程發送一個信號。調用了wait()的線程會貶稱inactive狀態,直到另外一個線程調用notify()。
需要注意的是,調用wait或者notify的線程必須要獲得這個對象的鎖。也就是說,一個線程必須在synchronized block中調用wait notify。

public class MonitorObject{
}

public class MyWaitNotify{
  MonitorObject myMonitorObject = new MonitorObject();

  public void doWait(){
    synchronized(myMonitorObject){
      try{
        myMonitorObject.wait();
      } catch(InterruptedException e){...}
    }
  }

  public void doNotify(){
    synchronized(myMonitorObject){
      myMonitorObject.notify();
    }
  }
}

Wouldn't the waiting thread keep the lock on the monitor object (myMonitorObject) as long as it is executing inside a synchronized block? Will the waiting thread not block the notifying thread from ever entering the synchronized block in doNotify()? The answer is no. Once a thread calls wait() it releases the lock it holds on the monitor object. This allows other threads to call wait() or notify() too, since these methods must be called from inside a synchronized block.
Once a thread is awakened it cannot exit the wait() call until the thread calling notify() has left its synchronized block. In other words: The awakened thread must reobtain the lock on the monitor object before it can exit the wait() call, because the wait call is nested inside a synchronized block. If multiple threads are awakened using notifyAll() only one awakened thread at a time can exit the wait() method, since each thread must obtain the lock on the monitor object in turn before exiting wait().

semaphore##

semaphore實現的功能就類似廁所有5個坑,假如有10個人要上廁所,那么同時只能有多少個人去上廁所呢?同時只能有5個人能夠占用,當5個人中 的任何一個人讓開后,其中等待的另外5個人中又有一個人可以占用了。

Semaphore semaphore = new Semaphore(5);

//critical section
semaphore.acquire();
...
semaphore.release();

除了acquire和release,Semaphor還提供了其他接口:

  • availablePermits()
  • acquireUninterruptibly()
  • drainPermits()
  • hasQueuedThreads()
  • getQueuedThreads()
  • tryAcquire()

CountDownLatch##

CyclicBarrier##

CyclicBarrier要做的事情是讓一組線程到達一個屏障時被阻塞,直到最后一個線程到達屏障時,屏障門才會打開。

public class CyclicBarrierTest {

    static CyclicBarrier c = new CyclicBarrier(2);

    public static void main(String[] args) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    c.await();
                } catch (Exception e) {

                }
                System.out.println(1);
            }
        }).start();

        try {
            c.await();
        } catch (Exception e) {

        }
        System.out.println(2);
    }
}

線程池#

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,923評論 6 535
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,740評論 3 420
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,856評論 0 380
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,175評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,931評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,321評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,383評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,533評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,082評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,891評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,067評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,618評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,319評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,732評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,987評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,794評論 3 394
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,076評論 2 375

推薦閱讀更多精彩內容