控制 Java 中的主线程

java 8object oriented programmingprogramming

可以通过实现 Runnable 接口并重写 run() 方法来创建线程。

Java 中的主线程是在程序启动时开始执行的线程。所有子线程都是从主线程生成的。此外,它是最后一个完成执行的线程,因为它执行各种关闭操作。

下面给出了一个演示此操作的程序:

示例

public class Demo {
   public static void main(String args[]) {
      Thread t = Thread.currentThread();
      System.out.println("Main thread: " + t);
      t.setName("current");
      System.out.println("Current thread: " + t);
      try {
         for (int i = 1; i <= 5; i++) {
            System.out.println(i);
            Thread.sleep(10);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread is interrupted");
      }
      System.out.println("Exiting the Main thread");
   }
}

输出

Main thread: Thread[main,5,main]
Current thread: Thread[current,5,main]
1
2
3
4
5
Exiting the Main thread

相关文章