Java中启动线程中启动线程start和和run的两种方法的两种方法
start()方法它的作用是启动一个新线程,run()就和普通的成员方法一样,可以被重复调用。接下来通过本文给大
家分享Java中启动线程start和run的两种方法,需要的朋友参考下吧
一、区别一、区别
Java中启动线程有两种方法,继承Thread类和实现Runnable接口,由于Java无法实现多重继承,所以一般通过实现Runnable
接口来创建线程。但是无论哪种方法都可以通过start()和run()方法来启动线程,下面就来介绍一下他们的区别。
start方法:方法:
通过该方法启动线程的同时也创建了一个线程,真正实现了多线程。无需等待run()方法中的代码执行完毕,就可以接着执行
下面的代码。此时start()的这个线程处于就绪状态,当得到CPU的时间片后就会执行其中的run()方法。这个run()方法包含了要
执行的这个线程的内容,run()方法运行结束,此线程也就终止了。
run方法:方法:
通过run方法启动线程其实就是调用一个类中的方法,当作普通的方法的方式调用。并没有创建一个线程,程序中依旧只有一
个主线程,必须等到run()方法里面的代码执行完毕,才会继续执行下面的代码,这样就没有达到写线程的目的。
下面我们通过一个很经典的题目来理解一下:
public class Test {
public static void main(String[] args) {
Thread t = new Thread(){
public void run() {
pong();
}
};
t.run();
System.out.println("ping");
}
static void pong() {
System.out.println("pong");
}
}
代码如图所示,那么运行程序,输出的应该是什么呢?没错,输出的是”pong ping”。因为t.run()实际上就是等待执行new
Thread里面的run()方法调用pong()完毕后,再继续打印”ping”。它不是真正的线程。
而如果我们将t.run();修改为t.start();那么,结果很明显就是”ping pong”,因为当执行到此处,创建了一个新的线程t并处于就绪
状态,代码继续执行,打印出”ping”。此时,执行完毕。线程t得到CPU的时间片,开始执行,调用pong()方法打印出”pong”。
如果感兴趣,还可以多加几条语句自己看看效果。
二、源码二、源码
那么他们本质上的区别在哪里,我们来看一下源码:
/**java
* 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.
*
评论0