大多数情况,通过实例化一个Thread对象来创建一个线程。Java定义了两种方式:
- 实现Runnable 接口;
- 可以继承Thread类。
例1. 实现Runnable接口
//7.4Java创建线程(Runnable接口和Thread类)
packagepackage1;
//创建一个实现Runnable 接口的类
classNewThread implements Runnable {
//通过thread类,声明对象t
Thread t;
//定义构建方法 NewThread
NewThread() {
//实例化一个Thread类的对象,第一个参数this表示调用方法run()启动线程执行,第二个参数"Demo Thread"表示线程名字
t=new Thread(this,"Demo Thread");
System.out.println("Child Thread:"+t);
//调用start()之后,NewThread 的构造函数返回到main()
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("ChildThread: " + i);
//子线程沉睡500毫秒
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Childinterrupted.");
}
System.out.println("Exiting child thread.");
}
}
public classThreadDemo {
public static voidmain(String args[]) {
new NewThread(); //create a new thread
try {
for(int i = 5; i> 0; i--) {
System.out.println("Main Thread: " + i);
//主线程沉睡1000毫秒
Thread.sleep(1000);
}
} catch(InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
结果:
ChildThread:Thread[Demo Thread,5,main]
Main Thread:5
ChildThread: 5
ChildThread: 4
ChildThread: 3
Main Thread:4
ChildThread: 2
ChildThread: 1
Main Thread:3
Exitingchild thread.
Main Thread:2
Main Thread:1
Main threadexiting.
解释:
- new NewThread 产生一个新的线程
- 在NewThread 构造函数中,新的Thread对象由下面的语句创建: t = new Thread(this, "Demo Thread");
- 通过前面的语句this 表明在this对象中你想要新的线程调用run()方法,以run()方法为开始启动了线程的执行,这使子线程for 循环开始执行。
- 然后,start() 被调用,调用start()之后,NewThread 的构造函数返回到main()。当主线程被恢复,它到达for 循环。两个线程继续运行,共享CPU,直到它们的循环结束。
- 需要注意的是子线程完成后,主线程才能完成
例2. 继承thread
//7.4Java创建线程(Thread类)
packagepackage1;
//Createa second thread by extending Thread
classNewThread2 extends Thread {
NewThread2() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread:" + this);
start(); // Start the thread
}
// This is the entry point for the secondthread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("ChildThread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Childinterrupted.");
}
System.out.println("Exiting childthread.");
}
}
publicclass ThreadDemo2 {
public static void main(String args[]) {
new NewThread2(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("MainThread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main threadinterrupted.");
}
System.out.println("Main threadexiting.");
}
}
结果:
ChildThread:Thread[Demo Thread,5,main]
Main Thread:5
ChildThread: 5
ChildThread: 4
ChildThread: 3
Main Thread:4
ChildThread: 2
ChildThread: 1
Main Thread:3
Exitingchild thread.
Main Thread:2
Main Thread:1
Main threadexiting.
解释:
- new NewThread2(); 创建一个新的线程
- super("Demo Thread"); 调用run()方法,以run()方法为开始启动了线程的执行
- 然后,start() 被调用,开始线程。调用start()之后,NewThread 的构造函数返回到main()。当主线程被恢复,它到达for 循环。两个线程继续运行,共享CPU,直到它们的循环结束。