可以通过实现Runnable接口并覆盖该run()方法来创建线程。然后可以创建一个Thread对象并start()调用该方法。
Java中的Main线程是程序启动时开始执行的线程。所有子线程都是从主线程派生的,它是完成执行的最后一个线程。
演示此过程的程序如下:
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("子线程被中断。");
}
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