多執行緒設計模式 保護性暫停模式

2021-10-11 11:16:41 字數 2215 閱讀 7986

保護性暫停模式就是提供了一種執行緒間通訊能力的模式。

如果有乙個執行緒的執行結果需要傳遞給另乙個執行緒,就需要使用保護性暫停模式將兩條執行緒關聯起來。

jdk中join方法和future就是使用了此模式實現的。

package com.leolee.multithreadprogramming.concurrent.guarded;

import lombok.extern.slf4j.slf4j;

/** * @classname test

* @description: 測試gurarded

* gurarded的作用:

* 如果有乙個執行緒的結果需要傳遞到另乙個執行緒,讓他們用gurarded做關聯

* jdk中join和future就是使用此模式實現的

* @author leolee

* @date 2020/12/5

* @version v1.0

**/@slf4j

public class test is waiting for response", thread.currentthread().getname());

log.info("response:{}", boolean.valueof(string.valueof(guardedobject.getresponse())));

}, "t1").start();

new thread(() -> executing something for response", thread.currentthread().getname());

try catch (interruptedexception e)

guardedobject.complete(true);

}, "t2").start();

}}class guardedobject catch (interruptedexception e)

}return response;}}

public object getresponse(long timeout)

try catch (interruptedexception e)

processtime = system.currenttimemillis() - begintime;

}return response;}}

//產生結果

public void complete(object response)

}}

join的原始碼是典型的保護性暫停模式:

/**

* waits at most milliseconds for this thread to

* die. a timeout of means to wait forever.

** this implementation uses a loop of calls

* conditioned on . as a thread terminates the

* method is invoked. it is recommended that

* on instances.

** @param millis

* the time to wait in milliseconds

** @throws illegalargumentexception

* if the value of is negative

** @throws interruptedexception

* if any thread has interrupted the current thread. the

* interrupted status of the current thread is

* cleared when this exception is thrown.

*/public final synchronized void join(long millis)

throws interruptedexception

if (millis == 0)

} else

wait(delay);

now = system.currenttimemillis() - base;}}

}

併發程式設計 保護性暫停模式

目錄 併發程式設計之保護性暫停模式 一 定義 guarded suspension design pattern 二 簡單實現 三 超時實現 四 最終實現 某個結果需要在多執行緒之間傳遞,則可以讓這些執行緒關聯到乙個物件guardedobject 但是這個物件需要不斷從乙個執行緒到另外乙個執行緒,那...

多執行緒設計模式

呼叫類 public class main 介面 public inte ce data 包裝類 public class futureclient start return futuredata 真實資料處理類 public class realdata implements data catch...

多執行緒設計模式

所謂 single threaded execution 即 以乙個執行緒執行 該模式用於設定限制,以確保同一時間內只讓乙個執行緒執行處理。immutable模式中存在著確保例項狀態不發生改變的類 immutable類 在訪問這些例項時並不需要執行耗時的互斥處理,因此若能巧妙利用該模式,定能提高程式...