3.6 執行緒通信
執行緒通信是指不同執行緒之間相互傳遞資訊,執行緒通信可以實作執行緒等待其他執行緒執行結果后再執行,這樣來實作不同執行緒之間按照有序的方式進行作業,
那么問題來了,Java要如何實作執行緒間通信呢?

3.6.1 實作通信–共享變數
可以通過共享變數來實作,實作思路就是一個通過一個共享變數狀態的改變來實作執行緒通信,下邊就從代碼來看下,

public class SignalDemo {
// private Object obj = new Object();
boolean singal = false;
public boolean isSingal() {
return singal;
}
public void setSingal(boolean singal) {
this.singal = singal;
}
public static void main(String[] args) {
SignalDemo signalDemo = new SignalDemo();
new Thread(()->{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
signalDemo.setSingal(true);
System.err.println("\r\n執行緒2修改信號值");
}).start();
while (!signalDemo.isSingal()){
System.err.print("k");
}
}
}

上例實作的就是一個執行緒作業,然后另一個執行緒通過改變共享變數來終止作業執行緒,Just it!
3.6.2 wait-notify機制
官方注釋:wait方法可以使當前執行緒進入等待直到其他執行緒呼叫了物件的notify或者notifyAll方法,該方法本質上呼叫的是wait(0).
* Causes the current thread to wait until another thread invokes the
* {@link java.lang.Object#notify()} method or the
* {@link java.lang.Object#notifyAll()} method for this object.
* In other words, this method behaves exactly as if it simply
* performs the call {@code wait(0)}.
現在了解了wait-notify的機制后看一個小demo,用兩個執行緒一個執行緒輸出0-100以內的奇數,一個執行緒輸出0-100以內的偶數,
class SignalDemo2{
Object myMonitorObject = new Object();
public void doWait(){
synchronized(myMonitorObject){
try{
myMonitorObject.wait();
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void doNotify(){
synchronized(myMonitorObject){
myMonitorObject.notify();
}
}
public static void main(String[] args) {
Object o = new Object();
AtomicInteger i= new AtomicInteger();
new Thread(()->{
synchronized (o){
while (i.get() <=100){
if (i.get() %2==0) {
System.err.println(Thread.currentThread() + ":" + i);
i.getAndIncrement();
try {
o.wait();
o.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Thread(()->{
synchronized (o){
while (i.get() <=100){
if (i.get() %2!=0) {
System.err.println(Thread.currentThread() + ":" + i);
i.getAndIncrement();
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
該實作原理非常簡單,當一個執行緒輸出奇數或者偶數后,就使當前執行緒進入等待狀態,并且通知對方操作, 注意:當使用wait-notify機制的時候不要使用String物件或者全域變數的wait方法,可能會由于String常量參考導致意想不到的結果,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/256784.html
標籤:java
下一篇:重寫的介紹/重寫與多載的區別
