A new thread is assigned for each instruction or request, and that thread performs processing. This is the Thread-Per-Message pattern.
Consider the following example. The Main class requests the Host class to display characters. The Host class creates and starts a thread that processes the request. The launched thread uses the Helper class to do the actual display.
(See this manual for the entire code)
Host.java
public class Host {
private final Helper helper = new Helper();
public void request(final int count, final char c) {
new Thread() {
public void run() {
helper.handle(count, c);
}
}.start();
}
}
Client role The Client role issues a request to the Host role. The Client role does not know how the Host role fulfills the request. In the sample program, the Main class played this role.
Host role When the Host role receives a request from the Client role, it creates a new thread and starts it. The newly created thread uses the Helper role to process the request. In the sample program, the Host class played this role.
Helper role The Helper role provides the Host role with the function of processing the request. A new thread created by the Host role uses the Helper role. In the sample program, the Helper class played this role.
** The order in which the handle method is processed in the Thread-Per-Message pattern is not always the same as the order in which the request method is called. Therefore, it is inappropriate to use this pattern when the order of processing is meaningful. ** **
** In the Thread-Per-Message pattern, the request method side does not wait for the handle method to complete. Therefore, the execution result of handle cannot be obtained on the request side. Therefore, this pattern is used when the processing result is not needed. ** If you want the result of processing, use Future pattern.
Relation Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 1) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 2) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 3) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 4) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 5) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 6) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 7) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 8)
Recommended Posts