Java中創建線程主要有三種方式:
- 繼承Thread類創建線程類
- 通過Runnable接口創建線程類
- 通過Callable和Future創建線程
一、繼承Thread類創建線程類
- 定義Thread類的子類,並重寫該類的run方法,該run方法的方法體就代表了線程要完成的任務。因此把run()方法稱爲執行體。
- 創建Thread子類的實例,即創建了線程對象。
- 調用線程對象的start()方法來啓動該線程。
package com.xuew.workpro;
public class FirstThreadTest extends Thread{
int i = 0;
//重寫run方法,run方法的方法體就是現場執行體
public void run() {
for(;i<100;i++){
System.out.println(getName()+" "+i);
}
}
public static void main(String[] args) {
for(int i = 0;i< 100;i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
if(i==20) {
new FirstThreadTest().start();
new FirstThreadTest().start();
}
}
}
}
二、通過Runnable接口創建線程類
- 定義runnable接口的實現類,並重寫該接口的run()方法,該run()方法的方法體同樣是該線程的線程執行體。
- 創建Runnable實現類的實例,並依此實例作爲Thread的target來創建Thread對象,該Thread對象纔是真正的線程對象。
- 調用線程對象的start()方法來啓動該線程。
package com.xuew.workpro;
public class RunnableThreadTest implements Runnable {
private int i;
public void run() {
for(i = 0;i <100;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
public static void main(String[] args) {
for(int i = 0;i < 100;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
if(i==20) {
RunnableThreadTest rtt = new RunnableThreadTest();
new Thread(rtt,"新線程1").start();
new Thread(rtt,"新線程2").start();
}
}
}
}
三、通過Callable和Future創建線程
- 創建Callable接口的實現類,並實現call()方法,該call()方法將作爲線程執行體,並且有返回值。
- 創建Callable實現類的實例,使用FutureTask類來包裝Callable對象,該FutureTask對象封裝了該Callable對象的call()方法的返回值。
- 使用FutureTask對象作爲Thread對象的target創建並啓動新線程。
- 調用FutureTask對象的get()方法來獲得子線程執行結束後的返回值
package com.xuew.workpro;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args) {
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for(int i = 0;i < 100;i++) {
System.out.println(Thread.currentThread().getName()+" 的循環變量i的值"+i);
if(i==20) {
new Thread(ft,"有返回值的線程").start();
}
}
try {
System.out.println("子線程的返回值:"+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception {
int i = 0;
for(;i<100;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
繼承Thread類和實現Runnable接口的區別?
由於Java只支持單繼承,在實現Runnable接口後還可以繼承其他類,而繼承Thread類之後就不能在繼承其他類了。所以一般使用實現Runnable接口的方法實現多線程。
Callable接口和Runnable接口的區別?
Callable接口的線程執行體是call(),而Runnable接口的線程執行體是run()
call()方法可以有返回值,也可以拋出異常。可以把Callable接口看做Runnable接口的增強版