如何在 Java 中创建线程

java 8object oriented programmingprogramming

可以通过实现 Runnable 接口并重写 run() 方法来创建线程。然后可以创建一个 Thread 对象并调用 start() 方法。

Java 中的主线程是在程序启动时开始执行的线程。所有子线程都是从主线程生成的,它是最后一个完成执行的线程。

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

示例

class ThreadDemo implements Runnable {
   Thread t;
   ThreadDemo() {
      t = new Thread(this, "Thread");
      System.out.println("Child thread: " + t);
      t.start();
   }
   public void run() {
      try {
         System.out.println("Child Thread");
         Thread.sleep(50);
      } catch (InterruptedException e) {
         System.out.println("The child thread is interrupted.");
      }
      System.out.println("Exiting the child thread");
   }
}
public class Demo {
   public static void main(String args[]) {
      new ThreadDemo();
      try {
         System.out.println("Main Thread");
         Thread.sleep(100);
      } catch (InterruptedException e) {
         System.out.println("The Main thread is interrupted");
      }
      System.out.println("Exiting the Main thread");
   }
}

输出

Child thread: Thread[Thread,5,main]
Main Thread
Child Thread
Exiting the child thread
Exiting the Main thread

相关文章