作为一名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方法结束!
版权声明:本文来源于网络,由知了堂搜集整理。
知了堂为大学生/初学者提供编程实践学习指导和服务,通过前沿项目实战、自有学习/实践平台、专业学习体系、形式多样的线上线下活动,让学习者真正掌握编程技能、具备编程实战经验,获得入职/职场晋升能力,同时知了堂着力打造一个有温度的学习社区,通过链接学习导师、举行社区活动、规范社区交流机制,为学习者提供交流、分享、项目组队等空间,共建最有价值的编程学习者成长社区。