併發程式設計之Wait和Notify

西召發表於2019-03-24

Background

相關概念

什麼是多執行緒

我們把組成程式(Program)各個部分稱為執行緒(Thread)。也可以說,執行緒就是程式中輕量級的程式(Process)。

多執行緒(Multithreading)是Java的一個特性,它可以允許一個程式的多個部分(也就是執行緒)併發地執行,以達到最大程度利用CPU的目的。

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

-- www.geeksforgeeks.org/multithread…

執行緒的狀態

執行緒的狀態

輪詢

Samples

我們把迴圈執行某個邏輯判斷,直到判斷條件為true才執行判斷體中的邏輯,叫做輪詢(Polling)。輪詢是會浪費一定的CPU資源的。

The process of testing a condition repeatedly till it becomes true is known as polling.Polling is usually implemented with the help of loops to check whether a particular condition is true or not. If it is true, certain action is taken. This waste many CPU cycles and makes the implementation inefficient.

-- www.geeksforgeeks.org/inter-threa…

下面提供一個輪詢的實現示例。

Message:

isAvailable初始值是false,設定為true以後執行輪詢體。

注意要使用執行緒安全的AtomicBoolean,如果使用boolean,在多執行緒情況下會有意想不到的結果。

import lombok.Getter;
import lombok.Setter;
import java.util.concurrent.atomic.AtomicBoolean;

@Setter
@Getter
public class Message {
    private AtomicBoolean isAvailable = new AtomicBoolean(false);
    private String msg;
    public Message(String str) {
        this.msg = str;
    }
}
複製程式碼

PollingWaiter:


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class PollingWaiter implements Runnable {
    private Message msg;
    public PollingWaiter(Message m) {
        this.msg = m;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            int count = 0;
            System.out.println(name + " : waiter starting at time: " + LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            while (!msg.getIsAvailable().get()) {
                count++;
            }
            System.out.println(name + " : msg is available at time: " + LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            System.out.println(name + " : msg is available after count: " + count);
            System.out.println(name + " : processed: " + msg.getMsg());
        }
    }
}

複製程式碼

執行測試:

休眠3秒以後,再執行輪詢體內的程式碼。

import java.util.concurrent.atomic.AtomicBoolean;

public class WaitNotifyTest {

    public static void main(String[] args) {
        testPolling();
    }

    public static void testPolling() {

        Message msg = new Message("process it");

        PollingWaiter waiter = new PollingWaiter(msg);

        new Thread(waiter, "PollingWaiter").start();

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        msg.setIsAvailable(new AtomicBoolean(true));
        System.out.println("over");
    }

}
複製程式碼

輸出結果:

PollingWaiter : waiter starting at time: 14:26:08.482
over
PollingWaiter : msg is available at time: 14:26:11.402
PollingWaiter : msg is available after count: -69547606
PollingWaiter : processed: process it
複製程式碼

wait 和 notify

除了輪詢,Java通過wait 和 notify機制實現了執行緒間的通訊。wait就是讓執有某個物件的執行緒處於等待阻塞狀態,而notify就是讓等待阻塞中的執行緒重新獲得CPU資源,再次進入執行狀態。

由於wait 和 notify相關的方法實現在了java.lang.Object類中,因此所有的子類都可以使用這些方法。

wait 和 notify相關的方法需要在synchronized程式碼塊中執行。

wait 和 notify

方法介紹

下面簡要介紹一下這些方法:

  • wait()

wait()方法會導致當前執行緒從執行狀態改為待執行狀態,一直到另外一個執行緒為當前物件執行notify()或者notifyAll()方法。

  • wait(long timeout)

wait()方法的不同點是,如果timeout時間到了以後,還沒有前物件執行notify()或者notifyAll(),則執行緒自動開始執行。

值得注意的是執行wait(0)wait()的效果是一樣的。

  • wait(long timeout, int nanos)

wait(long timeout)相比,此方法提供了等待超時設定的更高的精度,精確到了納秒。

1毫秒 = 1,000,000 納秒。

  • notify()

對於等待此物件的監視器的所有執行緒,執行notify()會隨機喚醒一個執行緒。

  • notifyAll()

相比與notify(),此方法會喚醒所有等待該物件的監視器的執行緒。

示例

在上面示例程式碼的基礎上,增加如下程式碼實現。

Waiter:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Waiter implements Runnable{

    private Message msg;

    public Waiter(Message m){
        this.msg=m;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" : waiting to get notified at time:"+ LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" : waiter thread got notified at time:"+LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            //process the message now
            System.out.println(name+" : processed: "+msg.getMsg());
        }
    }

}
複製程式碼

Notifier:

public class Notifier implements Runnable {

    private boolean isAll = true;

    private Message msg;

    public Notifier(Message msg, boolean isAll) {
        this.msg = msg;
        this.isAll = isAll;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " started");
        try {

            Thread.sleep(3000);

            synchronized (msg) {

                System.out.println(name + " : got the msg : "+msg.getMsg());

                msg.setMsg(name + " : Notifier work done");

                if (isAll) {
                    msg.notifyAll();
                } else {
                    msg.notify();
                }

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
複製程式碼

WaitNotifyTest:

import java.util.concurrent.atomic.AtomicBoolean;

public class WaitNotifyTest {

    public static void main(String[] args) {
        //testPolling();
        testNotify();
        //testNotifyAll();
    }

    public static void testPolling() {

        Message msg = new Message("process it");

        PollingWaiter waiter = new PollingWaiter(msg);

        new Thread(waiter, "PollingWaiter").start();

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        msg.setIsAvailable(new AtomicBoolean(true));
        System.out.println("over");
    }

    public static void testNotify() {
        Message msg = new Message("process it");

        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1, "waiter1").start();

        Waiter waiter2 = new Waiter(msg);
        new Thread(waiter2, "waiter2").start();

        Notifier notifier = new Notifier(msg, false);
        new Thread(notifier, "notifier").start();

        System.out.println("All the threads are started");
    }

    public static void testNotifyAll() {
        Message msg = new Message("process it");

        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1, "waiter1").start();

        Waiter waiter2 = new Waiter(msg);
        new Thread(waiter2, "waiter2").start();

        Notifier notifier = new Notifier(msg, false);
        new Thread(notifier, "notifier").start();

        System.out.println("All the threads are started");
    }
}

複製程式碼

在啟動兩個執行緒同時執行wait方法的時候,會發現notify以後只有一個執行緒被喚醒了,而另一個執行緒則陷入了無盡地等待之中。

Links

倉庫地址

github.com/javastudyde…

參考連結

相關文章