Welcome
admin
admin

2025-06-30 10:17:44

世界杯误判
1607 192

原文地址:http://www.geeksforgeeks.org/main-thread-java/

Java对多线程编程提供了内置的支持。一个多线程程序可以包含两个或者更多的并发部分。每一部分都称为一个线程,而且每个线程都定义为一个独立的执行路径。

Main Thread

当一个Java程序启动以后,有一个线程就会立马跑起来。这就是通常所说的Main线程,因为当我的程序一启动,它就开始执行了。

属性

大量其他的子线程都是从它这里产生的通常它都是最后一个结束执行的线程,因为它要做各种关闭的动作

流程图

如何控制main线程

当我们的程序启动以后,Main线程就自动被创建出来了。想要控制它,我们就得获取一个它的引用。这个可以通过调用currentThread()来做到,这个方法是在Thread类中。这个方法返回一个当前正在被调用的线程的引用。main线程的默认优先级是5,其他剩下的用户线程优先级都是子类继承基类。

// Java program to control the Main Thread

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");

}

}

}

输出:

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

main方法和Main线程之间的关系

对于每一个程序,Main线程都是由Java虚拟机创建的。Main线程首先要验证main()方法的存在,然后初始化这个类。注意从JDK 6开始main()被强制是一个独立的应用程序。

main线程的死锁(只有单个线程)

我们可以仅仅利用Main线程来创建一个死锁,例如,只用一个线程,下面的Java代码做了演示:

// Java program to demonstrate deadlock

// using Main thread

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();

}

}

}

输出:

Entering into Deadlock

解释

Thread.currentThread().join()的声明就告诉Main线程要等待这个线程(例如等待自己)。因此Main线程在等待他自己挂掉,也就是死锁么。