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