如何在Java中创建线程
可以通过实现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
热门推荐
10 新年元旦祝福语大全简短
11 年终聚餐祝福语简短独特
12 五十二新年祝福语简短
13 六一加端午祝福语简短
14 新年祝福语简短句子
15 二胎祝福语简短霸气
16 老婆生日祝福语短句简短
17 朋友搬迁新房祝福语简短
18 五一祝福语大全简短最新