推薦:Java并發程式設計彙總
啟動線程的正确姿勢
通過之前的分析,我們知道了有兩種定義線程執行邏輯的方法,而建立線程隻有一種方法,也就是
new
一個
Thread
類的執行個體。
JAVA實作多線程到底有多少種方法?
我們如何啟動線程呢?其實很簡單,調用
start()
即可。
package startThread;
public class test {
public static void main(String[] args) {
Runnable runnable = ()->{
System.out.println(Thread.currentThread().getName());
};
Thread thread = new Thread(runnable);
// 設定線程名稱
thread.setName("thread_kaven");
thread.start();
}
}
輸出:
thread_kaven
很顯然,
start()
啟動了線程,并且是在一個新的線程中去執行任務的,但是為什麼一定要調用
start()
,而不直接調用該線程的執行邏輯
run()
呢?
我們來測試調用
run()
的情況。
package startThread;
public class test {
public static void main(String[] args) {
Runnable runnable = ()->{
System.out.println(Thread.currentThread().getName());
};
Thread thread = new Thread(runnable);
// 設定線程名稱
thread.setName("thread_kaven");
thread.run();
}
}
輸出:
main
很顯然,調用
run()
,并沒有建立新的線程去執行任務,
run()
還是在
main
線程中執行的。
我們可以得到一個簡單的結論:
run()
隻是一個類中的普通方法,調用
run()
跟調用普通方法一樣。
而調用
start()
,則會做一系列工作去建立新線程,然後在新線程中執行
run()
裡面的任務内容。
我們可以多次調用
start()
嗎?我們來測試一下。
package startThread;
public class test {
public static void main(String[] args) {
Runnable runnable = ()->{
System.out.println(Thread.currentThread().getName());
};
Thread thread = new Thread(runnable);
// 設定線程名稱
thread.setName("thread_kaven");
thread.start();
thread.start();
}
}
輸出:
thread_kaven
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at startThread.test.main(test.java:13)
/**
* 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
* 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 */
}
}
}