前段時間有同事提到了主線程這個名詞,但當時咱們說的主線程是指Java Web
程序中每個請求進來時處理邏輯的線程。當時感受這個描述很奇怪,因此就來研究下這個主線程的確切語義。java
Java提供了內置的多線程編程支持,多線程包括兩個或多個可併發執行的部分,每一部分叫作線程,每一個線程定義了單獨的執行部分。編程
當一個Java程序啓動的時候,會有一個線程當即開始運行,這個線程一般被咱們叫作程序中的主線程,由於它是在咱們程序開始的時候就被執行的線程。多線程
流程圖:
併發
主線程在程序啓動時會被自動建立,爲了可以控制它咱們必須獲取到它的引用,咱們能夠在當前類中調用currentThread()
方法來獲取到,該方法返回一個當前線程的引用。ide
主線程默認的優先級是5,全部子線程都將繼承它的優先級。函數
public class Test extends Thread { public static void main(String[] args) { // getting reference to Main thread Thread t = Thread.currentThread(); // getting name of Main thread System.out.println("Current thread: " + t.getName()); // changing the name of Main thread t.setName("Geeks"); System.out.println("After name change: " + t.getName()); // getting priority of Main thread System.out.println("Main thread priority: " + t.getPriority()); // setting priority of Main thread to MAX(10) t.setPriority(MAX_PRIORITY); System.out.println("Main thread new priority: " + t.getPriority()); for (int i = 0; i < 5; i++) { System.out.println("Main thread"); } // Main thread creating a child thread ChildThread ct = new ChildThread(); // getting priority of child thread // which will be inherited from Main thread // as it is created by Main thread System.out.println("Child thread priority: " + ct.getPriority()); // setting priority of Main thread to MIN(1) ct.setPriority(MIN_PRIORITY); System.out.println("Child thread new priority: " + ct.getPriority()); // starting child thread ct.start(); } } // Child Thread class class ChildThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("Child thread"); } } }
看下輸出:.net
Current thread: main After name change: Geeks Main thread priority: 5 Main thread new priority: 10 Main thread Main thread Main thread Main thread Main thread Child thread priority: 10 Child thread new priority: 1 Child thread Child thread Child thread Child thread Child thread
對每一個程序而言,主線程都是被JVM建立的,從JDK6開始,main()方法在Java程序中是強制使用的。線程
咱們能夠使用主線程建立一個死鎖:code
public class Test { public static void main(String[] args) { try { System.out.println("Entering into Deadlock"); Thread.currentThread().join(); // the following statement will never execute System.out.println("This statement will never execute"); } catch (InterruptedException e) { e.printStackTrace(); } } }
看下輸出:blog
Entering into Deadlock
語句Thread.currentThread().join()
會告訴主線程一直等待這個線程(也就是等它本身)運行結束,因此咱們就有了死鎖。
關於Java中的死鎖和活鎖能夠參考這篇文章