Thread類中的start()和run()的區別說明
start():它的作用是啓動一個新的線程,新線程會執行相應的run()方法,start()不能被重複調用
run():run()就和普通的成員方法一樣,可以被重複調用,單獨調用run()的話,會在當前線程中執行run(),而並不會啓動新線程
下面來代碼說明一下
package com.tuhu.filt.javadata;
public class MyThread extends Thread{
private int ticket = 10;
public void run(){
for(int i =0;i < 20;i++){
if(this.ticket > 0){
System.out.println(
this.getName()
+ "賣票:ticket"
+this.ticket--
);
}
}
}
}
class TicketThreadTest{
public static void main(String[] args) {
long start = System.currentTimeMillis();
MyThread t1 = new MyThread();
// MyThread t2 = new MyThread();
// MyThread t3 = new MyThread();
t1.start();
long end = System.currentTimeMillis() - start;
System.out.println("單線程執行的時間爲"+end);
// t2.start();
// t3.start();
}
}
t1.start()會啓動一個新的線程,並在新線程中運行run()方法
而t1.run()則會直接在當前線程中運行run方法,也就是main線程,並不會啓動一個新的線程來運行run();
start()和run()的區別示例
package com.tuhu.filt.javadatathread;
public class MyThread extends Thread {
public MyThread(String name){
super(name);
}
public void run(){
System.out.println(
Thread.currentThread().getName()
+"is running"
);
}
}
class Demo{
public static void main(String[] args) {
Thread mythread = new MyThread("mythread");
System.out.println(
Thread.currentThread().getName()
+"call mythread.run()"
);
mythread.run();
System.out.println(
Thread.currentThread().getName()
+"call mythread.start"
);
mythread.start();
}
}
我們可以從上面的結果看出來 run試運行在main主線程上面的
start()啓動後會調用run()方法此時是運行在mythread上的
start 和 run()方法的相關源碼 基於1。7
public synchronized void start() {
// 如果線程不是"就緒狀態",則拋出異常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
// 將線程添加到ThreadGroup中
group.add(this);
boolean started = false;
try {
// 通過start0()啓動線程
start0();
// 設置started標記
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
我們可以看出來start()實際上是通過本地方法start0()啓動線程的
private native void start0();
Thread.java中run()的代碼如下
public void run() {
if (target != null) {
target.run();
}
}
targrt是一個Runnable()對象 run()就是直接調用Thread線程的Runnable成員的run()方法,並不會新建一個線程。也就是說我們最開始啓動main線程,他會直接去判斷main線程的Runnable成員的run()方法 明白了嗎?