前言
java創建線程的三種方式分別是繼承Thread類、 實現Runnable接口、 實現Callable接口。
繼承Thread
這種方式是通過新建繼承於Thread的類,並重寫run()方法來實現的,run()方法主要是指定你要讓這個線程爲你做什麼
public static void main(String[] args) {
Thread addThread = new AddThread();
addThread.start();
}
static class AddThread extends Thread
{
@Override
public void run() {
super.run();
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+" : 1+1的結果是"+(1+1));
}
}
}
執行結果
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
Thread-0 : 1+1的結果是2
實現Runnable接口
同樣是新建一個類,不同的是,不再繼承Thread類,而是去實現Runnable接口。
Runnable接口源碼如下,只有一個run方法。
public interface Runnable {
public abstract void run();
}
同樣,我們也要重寫run()方法來指定這個線程爲我們做什麼。
static class AddThreadWithRunnable implements Runnable
{
@Override
public void run() {
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+" : 2+2的結果是"+(2+2));
}
}
}
最後在主線程main方法中創建該線程,並調用start()方法來執行。
public static void main(String[] args) {
Thread addThread = new Thread(new AddThreadWithRunnable());
addThread.start();
}
實現Callable接口
這種方式與實現Runnable接口的不同之處在於,這種方式能夠獲取線程的執行結果。
下面是Callable接口的源碼,V是用於指定返回值的類型。
public interface Callable<V> {
V call() throws Exception;
}
同樣新建一個靜態內部類,實現Callable接口,這裏我們設置返回值的類型爲Integer,返回值爲2
static class AddThreadWithCallable implements Callable<Integer>
{
@Override
public Integer call() throws Exception {
return 1+1;
}
}
在主線程main中調用線程爲我們執行任務的方法與前兩種方法有些不一樣,
在實現Callable接口的方式中,我們需要做如下三步:
- 創建一個線程池
- 調用線程池的
submit()
方法,爲我們執行任務,並且返回結果Future對象 - 返回值可以通過Future對象的
get()
方法來獲取。
線程池不懂沒有關係,你暫時先只需要知道它是一個爲我們保存線程的“池子"。
public static void main(String[] args) {
//創建任務
AddThreadWithCallable task = new AddThreadWithCallable();
//新建一個線程池
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,10,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(5),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
//調用submit方法
Future<Integer> submit = executorService.submit(task);
try {
System.out.println("線程的返回結果是:"+submit.get());
} catch (Exception e) {
e.printStackTrace();
}
}
執行結果
線程的返回結果是:2
總結
日常實現Runnable接口來創建線程的方式用的多一些,Callable的方式也很重要,在未來開發中,能夠派上大用場。