前段时间有同事提到了主线程这个名词,但当时咱们说的主线程是指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中的死锁和活锁能够参考这篇文章