先说java中实现多线程常用的两种方式:
1:继承Thread类,并重写run()方法
2:实现Runnable接口,实现run方法
实际上Thread类也是实现了Runnable接口
[Java] 纯文本查看 复制代码?
123 | public class Thread implements Runnable { ........ } |
而Runnable接口只定义了一个run方法
[AppleScript] 纯文本查看 复制代码?
010203040506070809101112131415 | @FunctionalInterface public interface Runnable { / * * * When an object implementing interface < code > Runnable < / code > is used * to create a thread , starting the thread causes the object 's * < code > run < / code > method to be called in that separately executing * thread. * < p > * The general contract of the method < code > run < / code > is that it may * take any action whatsoever. * * @see java.lang.Thread #run() * / public abstract void run ( ) ; } |
我们需要实现的多线程业务逻辑,都需要在run方法内实现。
而start()是Thread中定义的方法,以下是start()方法的源码
[Java] 纯文本查看 复制代码?
01020304050607080910111213141516171819202122232425262728293031 | 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()通过调用本地native方法start0来启动一个线程,本地方法内最终会调用run方法,这样就可以实现在另一个线程中运行我们需要的代码。
而单独运行run()方法,就跟我们调用普通接口实现方法一样了,并不会启动新的线程.
总结:
1、start()方法运行时,本地启动新的线程,线程中会调用run方法,程序不需要等待run方法执行完毕再执行后面的程序;
2、run()方法是我们编写需要新的线程执行代码的方法,单独运行是不会有多线程效果的。
更多技术资讯可关注:itheimaGZ获取