Thread 中用到的两种设计模式
原创
©著作权归作者所有:来自51CTO博客作者Dongguabai的原创作品,请联系作者获取转载授权,否则将追究法律责任
其实有时候不能简单说哪种设计用到了哪些设计模式,设计模式本身就是对很多代码设计经验的总结。
模板模式
模板模式的应用就比较好理解了。在创建线程一般使用构建 Thread 类或者实现 Runnable 接口(这种说法是错误的,最起码是不严谨的,在 JDK 中代表线程的就只有 Thread 这个类,线程的执行单元就是 run() 方法,你可以通过继承 Thread 然后重写 run() 方法实现自己的业务逻辑,也可以实现 Runnable 接口实现自己的业务逻辑),启动线程是使用的 start() 方法,但是具体业务逻辑还是在 run() 方法中。
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
这样可以将业务逻辑和线程的逻辑分离。在模板设计模式在Thread的应用中看到了一个挺好的例子:
/**
* Description
* <p>
* </p>
* DATE 2018/10/26.
*
* @author caichengzhang.
*/
public class Template {
public Template() {
}
public final void start(){
System.out.println("stat方法启动!");
run();
System.out.println("start方法结束!");
}
public void run(){}
public static void main(String[] args) {
Template template = new Template(){
@Override
public void run() {
System.out.println("run方法开始运行!");
}
};
template.start();
}
}
策略模式
结合上面的 Thread 的 start() 方法,注释说明 start() 方法执行的是它的 run() 方法,再看看 Thread 的 run() 方法,如果构造传入 Runnable,就执行 Runnable 的 run() 方法,否则就需要重写 Thread 的 run() 方法。
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
/* What will be run. */
private Runnable target;
无论是 Runnable 的 run() 方法,还是 Thread 类本身的 run() 方法(事实上 Thread 类也是实现了 Runnable 接口)都是想将线程的控制本身和业务逻辑的运行分离开来,达到职责分明、功能单一的原则,这一点与 GoF 设计模式中的策略设计模式很相似。
这个 Runnable 就是策略接口,针对不同的策略实现,执行相应的方法。这样对策略进行不同的实现即可。
package com.example.threaddesign;
/**
* @author Dongguabai
* @date 2018/12/2 20:58
*/
public class ThreadTest {
public static void main(String[] args) {
Thread thread = new Thread(new Strategy1(), "执行者");
thread.start();
}
static class Strategy1 implements Runnable {
@Override
public void run() {
System.out.println("策略一");
}
}
static class Strategy3 implements Runnable {
@Override
public void run() {
System.out.println("策略三");
}
}
static class Strategy2 implements Runnable {
@Override
public void run() {
System.out.println("策略二");
}
}
}