Java 實現多線程的三種方式
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) {
//方法一:繼承Thread
int i = 0;
// for(; i < 100; i++){
// System.out.println(Thread.currentThread().getName() + " " + i);
// if (i == 5) {
// ThreadExtendsThread threadExtendsThread = new ThreadExtendsThread();
// threadExtendsThread.start();
// }
// }
//方法二:實現Runnable
// for(i = 0; i < 100; i++){
// System.out.println(Thread.currentThread().getName() + " " + i);
// if (i == 5) {
// Runnable runnable = new ThreadImplementsRunnable();
// new Thread(runnable).start();
// new Thread(runnable).start();
// }
// }
//方法三:實現Callable接口
Callable<Integer> callable = new ThreadImplementsCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
for(i = 0; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 5) {
new Thread(futureTask).start();
new Thread(futureTask).start();
}
}
try {
System.out.println("futureTask ruturn: " + futureTask.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法一,繼承自Thread
public class ThreadExtendsThread extends Thread {
private int i;
@Override
public void run() {
for(; i < 100; i++) {
System.out.println(getName() + " " + i);
}
}
}
run方法為線程執行體,ThreadExtendsThread對象即為線程對象。
方法二,實現Runnable接口
public class ThreadImplementsRunnable implements Runnable {
private int i;
@Override
public void run() {
for(; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
run方法為線程執行體,使用時New一個Thread對象,Runnable對象作為target傳遞給Thread對象。且同一個Runnable對象可作為多個Thread的target,這些線程均共享Runnable對象的實例變量。
方法三,實現Callable接口
import java.util.concurrent.Callable;
public class ThreadImplementsCallable implements Callable<Integer> {
private int i;
@Override
public Integer call() throws Exception {
for(; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
}
Callable接口類似於Runnable接口,但比對方強大,線程執行體為call方法,該方法具有返回值和可拋出異常。使用時將Callable對象包裝為FutureTask對象,通過泛型指定返回值類型。可稍候調用FutureTask的get方法取回執行結果。