初探Java主线程

一直对主线程这个东西雾里看花的感觉,可能是因为我没有去了解Java虚拟机相关知识的原因吧。

Java中的主线程

Java为多线程编程提供内置支持。多线程程序包含两个或多个可以并发运行的部分。这样的程序的每个部分称为线程,每个线程定义一个单独的执行路径。当Java程序启动时,一个线程立即开始运行。这通常被称为我们程序的线程,因为它是我们程序开始时执行的那个。

  • 它是生产启动其它线程的线程。
  • 它负责程序结束时候的收尾工作。

上面简单画图出一个主线程和子线程以及后台线程的关系。

在主线程中,这可以通过调用Thread类中的currentThread()方法来完成。此方法返回对其调用的线程的引用。主线程的默认优先级为5,对于所有剩余的用户线程,优先级将从父级继承到子级。同时虚拟机会启动其它的线程,比如垃圾回收器GC。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package cn.z201.java.test.thread;

/**
* @author z201.coding@gmail.com
**/
public class ChildThread extends Thread{

public ChildThread(String name) {
super(name);
}

@Override
public void run() {
for (int i = 0; i < 3 ; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package cn.z201.java.test.thread;

/**
* @author z201.coding@gmail.com
**/
public class MasterThread {

public static void main(String[] args) {

Thread master = Thread.currentThread();
// getting name of Main thread
System.out.println("Current thread: " + master.getName());

// changing the name of Main thread
master.setName("Master");
System.out.println("After name change: " + master.getName());

// getting priority of Main thread
System.out.println("Main thread priority: "+ master.getPriority());

// setting priority of Main thread to MAX(10)
master.setPriority(Thread.MAX_PRIORITY);

System.out.println("Main thread new priority: "+ master.getPriority());

for (int i = 0; i < 3; i++) {
System.out.println("MasterThread " + i);
}

ChildThread childThread1 = new ChildThread("childThread1");
// getting priority of child thread
// which will be inherited from Main thread
// as it is created by Main thread
System.out.println("Child1 thread priority: "+ childThread1.getPriority());
// setting priority of Main thread to MIN(1)
childThread1.setPriority(Thread.MIN_PRIORITY);
System.out.println("Child1 thread new priority: "+ childThread1.getPriority());

ChildThread childThread2 = new ChildThread("childThread2");
System.out.println("Child2 thread priority: "+ childThread2.getPriority());
childThread2.setPriority(Thread.NORM_PRIORITY);
System.out.println("Child2 thread new priority: "+ childThread2.getPriority());
// starting child thread
childThread1.start();
childThread2.start();

}
}

输出
Current thread: main
After name change: Master
Main thread priority: 5
Main thread new priority: 10
MasterThread 0
MasterThread 1
MasterThread 2
Child1 thread priority: 10
Child1 thread new priority: 1
Child2 thread priority: 10
Child2 thread new priority: 5
childThread1: 0
childThread1: 1
childThread1: 2
childThread2: 0
childThread2: 1
childThread2: 2

主线程默认优先级是5经过修改为10,启动的子线程就继承了主线程的级别。