作为一名java程序员,创建线程是工作中经常干的事情,也是面试中经常被提问的问题。大家都知道java中创建线程有两种最基本的方式:
- 创建Thread类;
- 实现runnable借口;
这两种方式有一个共同点就是我们的业务逻辑必须要实现run()这个方法,然后我们调用start()方法来启动线程。跟踪Thread的start()方法源码我们可以看到:
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 */
}
}
}
start()方法调用了一个start0()方法,而start0()方法源码如下:
private native void start0();
/**
* 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();
}
}
start0是一个native修饰的方法,而且它调用了run(),其实一点从设计模式上不能理解,这里用到的就是一个简单的模板模式,目的就是为了让业务的逻辑和线程的逻辑分离。以下是模板模式模拟线程的实现,希望有助于理解模板模式在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();
}
}
运行结果:
stat方法启动!
run方法开始运行!
start方法结束!