Java多線程建立與運作理了一下線程的建立和運作,可以看到線程最終都是通過
new一個Thread執行個體
,然後調用
start()方法
來運作的。
但是我們可以看到,一個線程的所要執行的任務方法體都是重寫到
run()
方法裡面的。
但是這裡是調用的start()方法來運作線程的,這說明start()方法做了一系列工作來建立一個線程運作run()方法裡面的行為,而不是從目前這個main()函數的線程去運作他。
線程的屬性 根據線程的屬性,我們可以自己設定線程的名稱。
Runnable runnable = ()->{
System.out.println(Thread.currentThread().getName());
};
Thread threadName = new Thread(runnable);
// 設定要建立的線程名稱
threadName.setName("codeXT");
threadName.start();
//如下方式并不會建立新線程執行run()方法
threadName.run();
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5CO4gzM3EzNzYWO4YTY0ImNzYzX0IjNzQTM5AzLcFTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
start()方法由synchronized修飾,synchronized修飾的資源相當于臨界資源,一個線程進去之後,其他線程調用會被阻塞挂起。而java線程和作業系統線程對應,會導緻使用者态到核心态的切換來執行阻塞,會引起上下文切換,時間耗費比較大。在退出synchronized修飾的資源時,會将共享變量的修改重新整理到主記憶體,來保證記憶體可見性。
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 */
}
}
}
if (threadStatus != 0)
throw new IllegalThreadStateException();
private volatile int threadStatus = 0;