Java中的主线程

概览

前段时间有同事提到了主线程这个名词,但当时我们说的主线程是指Java Web程序中每一个请求进来时处理逻辑的线程。当时感觉这个描述很奇怪,所以就来研究下这个主线程的确切语义。

Java提供了内置的多线程编程支持,多线程包括两个或多个可并发执行的部分,每一部分叫做线程,每个线程定义了单独的执行部分。

主线程

当一个Java程序启动的时候,会有一个线程立即开始运行,这个线程通常被我们叫做程序中的主线程,因为它是在我们程序开始的时候就被执行的线程。

  • 子线程都从该线程中被孵化
  • 通常它都是最后一个执行结束的线程,因为它会执行各种的关闭操作。

流程图:
Java主线程流程图

怎么来控制主线程

主线程在程序启动时会被自动创建,为了能够控制它我们必须获取到它的引用,我们可以在当前类中调用currentThread()方法来获取到,该方法返回一个当前线程的引用。

主线程默认的优先级是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");
        }
    }
}

看下输出:

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()函数的关系

对每个程序而言,主线程都是被JVM创建的,从JDK6开始,main()方法在Java程序中是强制使用的。

主线程中的死锁(单个线程)

我们可以使用主线程创建一个死锁:

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()会告诉主线程一直等待这个线程(也就是等它自己)运行结束,所以我们就有了死锁。

关于Java中的死锁和活锁可以参考这篇文章

猜你喜欢

转载自www.cnblogs.com/mrcharleshu/p/13190618.html