1. 繼承Thread類
2. 實現Runnable接口
3. 實現Callable接口,使用FutureTask方式
4. 使用線程池
1. 繼承Thread類
package com.pimee.thread;
/**
* 繼承Thread創建線程
* @author Bruce Shaw
*
*/
public class ThreadTest extends Thread {
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
test.start();
}
@Override
public void run() {
System.out.println("This is TestThread...");
}
}
2. 實現Runnable接口
package com.pimee.thread;
/**
* 實現runnable接口創建線程
* @author Bruce Shaw
*
*/
public class RunnableTest implements Runnable {
private static int test = 10;
@Override
public void run() {
System.out.println("This is RunnableTest...");
}
public static void main(String[] args) {
RunnableTest test = new RunnableTest();
new Thread(test).start();
}
}
以上兩種方式實現都比較簡單,缺點很明顯,就是線程執行後沒有返回值。且看下面帶有返回值的實現方式:
3. 實現Callable接口,使用FutureTask方式
package com.pimee.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeoutException;
/**
* 實現callable接口,基於FutureTask方式實現
* @author Bruce Shaw
*
*/
public class CallableTest implements Callable<String> {
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
CallableTest mc = new CallableTest();
FutureTask<String> ft = new FutureTask<>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
@Override
public String call() throws Exception {
System.out.println("Callable is running...");
return "Callable finished and return value...";
}
}
4. 使用線程池
package com.pimee.thread;
import java.util.concurrent.*;
/**
* 基於線程池創建
*
* @author Bruce Shaw
*
*/
public class ThreadPoolTest implements Callable<String> {
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
ExecutorService newCachedThreadPool = Executors.newSingleThreadExecutor();
Future<String> future = newCachedThreadPool.submit(new CallableTest());
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
} finally {
newCachedThreadPool.shutdown();
}
}
@Override
public String call() throws Exception {
System.out.println("Callable is running...");
return "Callable finished and return value...";
}
}
嚴格意義上來說,只是3種實現方式,因爲最後一種方式的實現是池化,可以創建上面Thread、Runnable、Callable的任意一種任務。
代碼已提交於:https://gitee.com/pimee/pm-test/tree/master/pm-thread/src/main/java/com/pimee/thread