1)繼承Thread類創建線程
public class MyThread extends Thread{//繼承Thread類
public void run(){
//重寫run方法
}
}
public class Main {
public static void main(String[] args){
new MyThread().start();//創建並啓動線程
}
}
2)實現Runnable接口創建線程
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" this is a thread");
}
}).start();
//lambed表達式
new Thread(() -> System.out.println(" this is a thread")).start();
3.通過Callable和Future創建線程
>boolean cancel(boolean mayInterruptIfRunning):視圖取消該Future裏面關聯的Callable任務
>V get():返回Callable裏call()方法的返回值,調用這個方法會導致程序阻塞,必須等到子線程結束後纔會得到返回值
>V get(long timeout,TimeUnit unit):返回Callable裏call()方法的返回值,最多阻塞timeout時間,經過指定時間沒有返回拋出TimeoutException
>boolean isDone():若Callable任務完成,返回True
>boolean isCancelled():如果在Callable任務正常完成前被取消,返回True
public class Dame2 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int count = 2;
return count * 10;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Dame2 test = new Dame2();
FutureTask<Integer> thread = new FutureTask<>(test);
new Thread(thread, "有返回值的線程").start();
System.out.println(thread.get());
}
}
//用lambda的寫法:
public class Dame2 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<Integer> thread = new FutureTask<>( ()->{
int count = 2;
return count * 10;
});
new Thread(thread, "有返回值的線程").start();
System.out.println(thread.get());
}
}
三種創建線程方法對比
實現Runnable和實現Callable接口的方式基本相同,不過是後者執行call()方法有返回值,後者線程執行體run()方法無返回值,因此可以把這兩種方式歸爲一種,這種方式與繼承Thread類的方法之間的差別如下:
1、線程只是實現Runnable或實現Callable接口,還可以繼承其他類。
2、這種方式下,多個線程可以共享一個target對象,非常適合多線程處理同一份資源的情形。
3、但是編程稍微複雜,如果需要訪問當前線程,必須調用Thread.currentThread()方法。
4、繼承Thread類的線程類不能再繼承其他父類(Java單繼承決定)。