本文主要是介绍多线程设计模式:Thread-Per-Message模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为每个命令或请求新分配一个线程,由这个线程来执行处理,这就是Thread-Per-Message模式。
举个例子:
名字 | 说明 |
---|---|
Main | 向Host发送字符,显示请求的类 |
Host | 针对请求创建线程的类 |
Helper | 提供字符显示功能的被动类 |
代码:
Main:
public class Main {public static void main(String[] args) {System.out.println("main BEGIN");Host host = new Host();host.request(10, 'A');host.request(20, 'B');host.request(30, 'C');System.out.println("main END");}
}
Host:
public class Host {private final Helper helper = new Helper();public void request(final int count, final char c) {System.out.println(" request(" + count + ", " + c + ") BEGIN");new Thread(() -> helper.handle(count, c)).start();System.out.println(" request(" + count + ", " + c + ") END");}
}
Helper:
public class Helper {// 用于按指定次数显示字符的handle方法public void handle(int count, char c){System.out.println(" handle(" + count + ", " + c + ") BEGIN");for (int i = 0; i < count; i++) {slowly();System.out.print(c);}System.out.println("");System.out.println(" handle(" + count + ", " + c + ") END");}private void slowly() {try {Thread.sleep(100);} catch (InterruptedException e) {}}
}
执行结果:
main BEGINrequest(10, A) BEGINrequest(10, A) ENDrequest(20, B) BEGINrequest(20, B) ENDrequest(30, C) BEGINhandle(10, A) BEGINhandle(20, B) BEGINrequest(30, C) END
main ENDhandle(30, C) BEGIN
BCAABCBCABACBACBCAABCBACBACCAhandle(10, A) END
BBCBCCBBCCBBCCBBCCBCBhandle(20, B) END
CCCCCCCCCChandle(30, C) END
可以看出调用request方法
这篇关于多线程设计模式:Thread-Per-Message模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!