如何在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 分手祝福语简短短句