日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

java 线程 设计模式_Java多线程设计模式(四)

發(fā)布時(shí)間:2023/12/16 java 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 线程 设计模式_Java多线程设计模式(四) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Future Pattern

在Thread-Per-Message Pattern中,我們研究過(guò)“收到每個(gè)請(qǐng)求建立一個(gè)線(xiàn)程”的做法,但這樣的請(qǐng)求是不要求有返回值的。如果當(dāng)需要返回值,但由于后臺(tái)處理需要很久,返回值 不能馬上獲取,那么就可以使用 Future Pattern。Future Pattern同樣會(huì)每個(gè)請(qǐng)求建立一個(gè)線(xiàn)程處理,同時(shí)會(huì)馬上返回一個(gè)對(duì)象,但該對(duì)象并不是真正的返回值,真正的返回值可能現(xiàn)在還沒(méi)有準(zhǔn)備好,不過(guò)客戶(hù)端可 以根據(jù)這個(gè)返回對(duì)象,在之后的時(shí)間來(lái)獲取真正的返回值。

public?interface?Data?{

public?String?getContent();

}

public?class?RealData?implements?Data?{

private?String?content;

public?RealData(int?count,?char?c)?{

System.out.println("making?RealData("?+?count?+?",?"?+?c?+?")?Begin.");

char[]?buffer?=?new?char[count];

for?(int?i?=?0;?i?

buffer[i]?=?c;

slowly();

}

this.content?=?String.valueOf(buffer);

System.out.println("making?RealData("?+?count?+?",?"?+?c?+?")?End.");

}

@Override

public?String?getContent()?{

return?this.content;

}

private?void?slowly()?{

try?{

Thread.sleep(100);

}?catch?(InterruptedException?e)?{

}

}

}

public?class?FutureData?implements?Data?{

private?RealData?realData;

private?boolean??ready?=?false;

public?synchronized?void?setRealData(RealData?realData)?{

if?(ready)?{

return;

}

this.realData?=?realData;

this.ready?=?true;

notifyAll();

}

@Override

public?synchronized?String?getContent()?{

while?(!ready)?{

try?{

wait();

}?catch?(InterruptedException?e)?{

}

}

return?this.realData.getContent();

}

}

public?class?Host?{

public?Data?handle(final?int?count,?final?char?c)?{

System.out.println("handle?(?"?+?count?+?",?"?+?c?+?")?Begin.");

final?FutureData?futureData?=?new?FutureData();

new?Thread()?{

@Override

public?void?run()?{

RealData?realData?=?new?RealData(count,?c);

futureData.setRealData(realData);

}

}.start();

System.out.println("handle?(?"?+?count?+?",?"?+?c?+?")?End.");

return?futureData;

}

}

public?class?Main?{

public?static?void?main(String[]?args)?{

System.out.println("main?Begin.");

Host?host?=?new?Host();

Data?data1?=?host.handle(10,?'a');

Data?data2?=?host.handle(20,?'b');

Data?data3?=?host.handle(30,?'c');

System.out.println("main?other?job?Begin.");

try?{

Thread.sleep(2000);

}?catch?(InterruptedException?e)?{

}

System.out.println("main?other?job?End.");

System.out.println("data1?=?"?+?data1.getContent());

System.out.println("data2?=?"?+?data2.getContent());

System.out.println("data3?=?"?+?data3.getContent());

System.out.println("main?End.");

}

}

在Worker Thread Pattern中,我們討論過(guò)“方法調(diào)用”和“方法執(zhí)行”的分離。而Future Pattern 分離了“準(zhǔn)備返回值”和“使用返回值”。我們?cè)贔uttern Pattern中,可以看到設(shè)計(jì)模式Proxy Pattern的實(shí)現(xiàn)。

Two-Phase Termination Pattern

Two-Phase Termination

Pattern很簡(jiǎn)單,但該模式提供了一種結(jié)束線(xiàn)程的優(yōu)雅方法。java.lang.Thread類(lèi)有一個(gè)用來(lái)強(qiáng)制結(jié)束掉線(xiàn)程的stop()方法。但是

stop方法已經(jīng)不建議使用(deprecated),原因是stop()方法會(huì)使實(shí)例喪失安全性的保障。使用stop()方法時(shí),線(xiàn)程會(huì)拋出

java.lang.ThreadDeath異常而馬上結(jié)束,即使該線(xiàn)程現(xiàn)在正在執(zhí)行靈界區(qū)間(例如synchronized方法的中間),也會(huì)馬上結(jié)

束。

public?class?CountupThread?extends?Thread?{

private?boolean?isShutdown?=?false;

private?int?????count??????=?0;

@Override

public?void?run()?{

try?{

while?(isShutdown)?{

doWork();

}

}?catch?(InterruptedException?e)?{

}?finally?{

doShutdown();

}

}

public?void?shutdownReqeust()?{

this.isShutdown?=?true;

interrupt();

}

private?void?doShutdown()?{

System.out.println("doShutdown:?current?count?is?"?+?this.count);

}

private?void?doWork()?throws?InterruptedException?{

System.out.println("curren?count?is?"?+?++count);

Thread.sleep(500);

}

public?static?void?main(String[]?args)?{

System.out.println("main?Begin.");

CountupThread?countupThread?=?new?CountupThread();

countupThread.start();

try?{

Thread.sleep(100000);

}?catch?(InterruptedException?e)?{

}

System.out.println("main?:?shutdown?request.");

countupThread.shutdownReqeust();

System.out.println("main?:?join");

//?等待線(xiàn)程結(jié)束

try?{

countupThread.join();

}?catch?(InterruptedException?e)?{

}

System.out.println("main?End.");

}

}

Thread-Specific Storage Pattern

Thread-Specific Storage

Pattern就是“線(xiàn)程獨(dú)有的存儲(chǔ)庫(kù)”、“針對(duì)每個(gè)線(xiàn)程提供的內(nèi)存空間”的意義。java.lang.ThreadLocal的實(shí)例可以想象成一種集合

架構(gòu)(collection)或許會(huì)比較好理解。ThreadLocal的實(shí)例只有一個(gè),管理多個(gè)對(duì)象。

public?class?Log?{

private?static?final?ThreadLocal?tsLogCollection?=?new?ThreadLocal();

public?static?void?println(String?s)?{

getTSLog().printWrite(s);

}

public?static?void?close()?{

getTSLog().close();

}

private?static?TSLog?getTSLog()?{

TSLog?tsLog?=?tsLogCollection.get();

//?如果線(xiàn)程時(shí)第一次調(diào)用,新建立新文件并注冊(cè)log

if?(tsLog?==?null)?{

tsLog?=?new?TSLog(Thread.currentThread().getName()?+?"-log.txt");

tsLogCollection.set(tsLog);

}

return?tsLog;

}

}

import?java.io.FileNotFoundException;

import?java.io.PrintWriter;

public?class?TSLog?{

private?PrintWriter?writer;

public?TSLog(String?filename)?{

try?{

this.writer?=?new?PrintWriter(filename);

}?catch?(FileNotFoundException?e)?{

}

}

public?void?printWrite(String?s)?{

writer.println(s);

}

public?void?close()?{

writer.println("===========End?of?log===========");

writer.close();

}

}

public?class?ClientThread?extends?Thread?{

public?ClientThread(String?name)?{

super(name);

}

@Override

public?void?run()?{

System.out.println(getName()?+?"?Begin.");

for?(int?i?=?0;?i?

Log.println("i?=?"?+?i);

try?{

Thread.sleep(100);

}?catch?(InterruptedException?e)?{

}

}

Log.close();

System.out.println(getName()?+?"?End.");

}

public?static?void?main(String[]?args)?{

new?ClientThread("Alice").start();

new?ClientThread("Bobby").start();

new?ClientThread("Chris").start();

}

}

Active Object Pattern

Active Object

Pattern其實(shí)可以看作是多個(gè)多線(xiàn)程模式和多個(gè)設(shè)計(jì)模式組合成的一種更高級(jí)的模式,里面多個(gè)對(duì)象各司其職,共同協(xié)作。Active Object

Pattern里面使用到了Producer-Consumer Pattern、Thread-Per-Message Pattern、Future

Pattern和設(shè)計(jì)模式的Proxy Pattern、Command Pattern等。

Server端代碼:

public?interface?ActiveObject?{

public?Result?makeString(int?count,?char?fillchar);

public?void?displayString(String?string);

}

public?class?Proxy?implements?ActiveObject?{

private?SchedulerThread?scheduler;

private?Servant?????????servant;

public?Proxy(SchedulerThread?scheduler,?Servant?servant)?{

this.scheduler?=?scheduler;

this.servant?=?servant;

}

@Override

public?Result?makeString(int?count,?char?fillchar)?{

FutureResult?future?=?new?FutureResult();

MakeStringRequest?request?=?new?MakeStringRequest(servant,?future,?count,?fillchar);

this.scheduler.invoke(request);

return?future;

}

@Override

public?void?displayString(String?string)?{

DisplayStringRequest?request?=?new?DisplayStringRequest(servant,?string);

this.scheduler.invoke(request);

}

}

public?class?Servant?implements?ActiveObject?{

@Override

public?Result?makeString(int?count,?char?fillchar)?{

char[]?buffer?=?new?char[count];

for?(int?i?=?0;?i?

buffer[i]?=?fillchar;

try?{

Thread.sleep(500);

}?catch?(InterruptedException?e)?{

}

}

RealResult?result?=?new?RealResult(String.valueOf(buffer));

return?result;

}

@Override

public?void?displayString(String?string)?{

System.out.println("displayString(?"?+?string?+?"?)");

try?{

Thread.sleep(10);

}?catch?(InterruptedException?e)?{

}

}

}

public?interface?Result?{

public?String?getResultValue();

}

public?class?FutureResult?implements?Result?{

private?Result??result;

private?boolean?isReady?=?false;

public?synchronized?void?setResult(Result?result)?{

if?(isReady)?{

return;

}

this.result?=?result;

this.isReady?=?true;

notifyAll();

}

@Override

public?synchronized?String?getResultValue()?{

while?(!isReady)?{

try?{

wait();

}?catch?(InterruptedException?e)?{

}

}

return?result.getResultValue();

}

}

public?class?RealResult?implements?Result?{

private?String?resultValue;

public?RealResult(String?resultValue)?{

this.resultValue?=?resultValue;

}

@Override

public?String?getResultValue()?{

return?this.resultValue;

}

}

public?abstract?class?MethodRequest?{

protected?final?Servant??????servant;

protected?final?FutureResult?future;

public?MethodRequest(Servant?servant,?FutureResult?future)?{

this.servant?=?servant;

this.future?=?future;

}

public?abstract?void?execute();

}

public?class?MakeStringRequest?extends?MethodRequest?{

private?int??count;

private?char?fillchar;

public?MakeStringRequest(Servant?servant,?FutureResult?future,?int?count,?char?fillchar)?{

super(servant,?future);

this.count?=?count;

this.fillchar?=?fillchar;

}

@Override

public?void?execute()?{

Result?result?=?this.servant.makeString(count,?fillchar);

future.setResult(result);

}

}

public?class?DisplayStringRequest?extends?MethodRequest?{

private?String?string;

public?DisplayStringRequest(Servant?servant,?String?string)?{

super(servant,?null);

this.string?=?string;

}

@Override

public?void?execute()?{

this.servant.displayString(string);

}

}

public?class?SchedulerThread?extends?Thread?{

private?ActivationQueue?queue?=?new?ActivationQueue();

public?void?invoke(MethodRequest?request)?{

this.queue.putRequest(request);

}

@Override

public?void?run()?{

while?(true)?{

this.queue.takeRequest().execute();

}

}

}

package?activeobject.server;

import?java.util.LinkedList;

public?class?ActivationQueue?{

private?final?LinkedList?requestQueue?=?new?LinkedList();

private?final?int???????????????????????queueSize????=?100;

public?synchronized?void?putRequest(MethodRequest?request)?{

while?(this.requestQueue.size()?>=?queueSize)?{

try?{

wait();

}?catch?(InterruptedException?e)?{

}

}

this.requestQueue.addLast(request);

notifyAll();

}

public?synchronized?MethodRequest?takeRequest()?{

while?(this.requestQueue.size()?==?0)?{

try?{

wait();

}?catch?(InterruptedException?e)?{

}

}

MethodRequest?request?=?this.requestQueue.removeFirst();

notifyAll();

return?request;

}

}

public?class?ActiveObjectFactory?{

public?static?ActiveObject?createActiveObjcet()?{

Servant?servant?=?new?Servant();

SchedulerThread?scheduler?=?new?SchedulerThread();

Proxy?proxy?=?new?Proxy(scheduler,?servant);

scheduler.start();

return?proxy;

}

}

UML如下圖:

客戶(hù)端代碼:

import?activeobject.server.ActiveObject;

public?class?DisplayClientThread?extends?Thread?{

private?ActiveObject?activeObj;

public?DisplayClientThread(String?name,?ActiveObject?activeObj)?{

super(name);

this.activeObj?=?activeObj;

}

@Override

public?void?run()?{

int?i?=?0;

while?(true)?{

i++;

String?string?=?getName()?+?"?No."?+?i;

activeObj.displayString(string);

}

}

}

import?activeobject.server.ActiveObject;

import?activeobject.server.Result;

public?class?MakerClientThread?extends?Thread?{

private?final?ActiveObject?activeObj;

private?final?char?????????fillchar;

public?MakerClientThread(String?name,?ActiveObject?activeObj)?{

super(name);

this.activeObj?=?activeObj;

this.fillchar?=?name.charAt(0);

}

@Override

public?void?run()?{

int?i?=?0;

while?(true)?{

i++;

Result?result?=?activeObj.makeString(i,?fillchar);

try?{

Thread.sleep(1000);

}?catch?(InterruptedException?e)?{

}

String?resultValue?=?result.getResultValue();

System.out.println(Thread.currentThread().getName()?+?":value?=?"?+?resultValue);

}

}

}

import?activeobject.server.ActiveObject;

import?activeobject.server.ActiveObjectFactory;

public?class?Main?{

public?static?void?main(String[]?args)?{

ActiveObject?activeObj?=?ActiveObjectFactory.createActiveObjcet();

new?MakerClientThread("Alice",?activeObj).start();

new?MakerClientThread("Bobby",?activeObj).start();

new?DisplayClientThread("Chris",?activeObj).start();

}

}

總結(jié)

以上是生活随笔為你收集整理的java 线程 设计模式_Java多线程设计模式(四)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。