咱們把組成程序(Program)各個部分稱爲線程(Thread)。也能夠說,線程就是程序中輕量級的進程(Process)。java
多線程(Multithreading)是Java的一個特性,它能夠容許一個程序的多個部分(也就是線程)併發地執行,以達到最大程度利用CPU的目的。git
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.github
咱們把循環執行某個邏輯判斷,直到判斷條件爲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.併發
下面提供一個輪詢的實現示例。oop
Message:測試
isAvailable
初始值是false,設置爲true之後執行輪詢體。this
注意要使用線程安全的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
複製代碼
除了輪詢,Java經過wait 和 notify機制實現了線程間的通訊。wait就是讓執有某個對象的線程處於等待阻塞狀態,而notify就是讓等待阻塞中的線程從新得到CPU資源,再次進入運行狀態。
因爲wait 和 notify相關的方法實如今了java.lang.Object
類中,所以全部的子類均可以使用這些方法。
wait 和 notify相關的方法須要在synchronized
代碼塊中執行。
下面簡要介紹一下這些方法:
wait()
方法會致使當前線程從執行狀態改成待執行狀態,一直到另一個線程爲當前對象執行notify()
或者notifyAll()
方法。
與wait()
方法的不一樣點是,若是timeout
時間到了之後,尚未前對象執行notify()
或者notifyAll()
,則線程自動開始執行。
值得注意的是執行wait(0)
和wait()
的效果是同樣的。
與wait(long timeout)
相比,此方法提供了等待超時設置的更高的精度,精確到了納秒。
1毫秒 = 1,000,000 納秒。
對於等待此對象的監視器的全部線程,執行notify()
會隨機喚醒一個線程。
相比與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之後只有一個線程被喚醒了,而另外一個線程則陷入了無盡地等待之中。
完整示例代碼請參考: