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.
線程的狀態
輪詢
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.
– https://www.geeksforgeeks.org/inter-thread-communication-java/
下面提供一個輪詢的實現示例。
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()
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以後只有一個線程被喚醒了,而另一個線程則陷入了無盡地等待之中。