1.start()方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码:
通过调用Thread类的start()方法来启动一个线程,
这时此线程是处于就绪状态,
并没有运行。
然后通过此Thread类调用方法run()来完成其运行操作的,
这里方法run()称为线程体,
它包含了要执行的这个线程的内容,
Run方法运行结束,
此线程终止,
而CPU再运行其它线程,
2.run()方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码:
而如果直接用Run方法,
这只是调用一个方法而已,
程序中依然只有主线程--这一个线程,
其程序执行路径还是只有一条,
这样就没有达到写线程的目的。
通过implements Runnable接口来实现多线程
示例代码:
代码如下 | 复制代码 |
package com; public class TestRunnable implements Runnable{ public TestRunnable(int num) { //实现方法 |
上例打印出来的结果是无序的:
1 4 3 2 0
也可能是别的顺序,通过Thread类调用start,真正实现了多线程,不用等待run方法执行完毕再起新线程。
如果将
代码如下 | 复制代码 |
new Thread(new TestRunnable(i)).start() 改成 new Thread(new TestRunnable(i)).run(), |
则打印出来的结果是由顺序的,也就是:
0 1 2 3 4
通过Thread类直接调用run方法,实际上就是调用TestRunnable类的run方法,查看Thread类的run方法:
代码如下 | 复制代码 |
public void run() { |
发现Thread类run方法就是调用了TestRunnable的run(),所以通过
代码如下 | 复制代码 |
new Thread(new TestRunnable(i)).run() |
并不是多线程,其执行线程还是主线程。
下面再将Thread类的start方法贴出来,可与上面Thread类的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 boolean started = false; |