1. 程式人生 > >Java併發程式設計(二)多執行緒四種實現方式

Java併發程式設計(二)多執行緒四種實現方式

Java實現多執行緒的方式

Java實現多執行緒的方式有4種:

繼承Thread方法、實現Runnable介面、實現Callable介面並通過FutureTask建立執行緒、使用ExecutorService。

其中,前兩種執行緒執行結果沒有返回值,後兩種是有返回值的。

1、繼承Thread方法

Thread類實現了Runnable介面,通過呼叫start()方法啟動執行緒。

這種方式實現多執行緒,通過繼承Thread類,並在複寫的run方法中實現業務邏輯。

// Thread測試用例
public class MyThread extends Thread{

	@Override
	public void run() {
		System.out.println("local logic for Thread test.");
	}

	public static void main(String[] args) {
		MyThread myThread = new MyThread();
		myThread.start();
	}
}

 

2、實現Runnable介面

這種方式通過直接實現Runnable介面,由於業務類需要藉助於Thread類的start方法等功能,因此,通過例項化的Thread類,來進行業務邏輯呼叫(呼叫start方法後會執行run方法)。

// Runnable 測試用例
public class MyThread2 implements Runnable {

	@Override
	public void run() {
		System.out.println("local logic for Runnable test.");
	}

	public static void main(String[] args) {
		MyThread2 myThread = new MyThread2();
		Thread thread = new Thread(myThread);
		thread.start();
	}
}

3、實現Callable介面並通過FutureTask建立執行緒

Callable和Runnable的區別主要在於,前者有返回值。

FutureTask實現了RunnableFuture介面,而RunnableFuture介面繼承了Runnable和Future介面,通過Future介面可以得到任務執行的一些資訊,Future介面介紹如下:

public interface Future<V> {
    //取消任務,如果任務正在執行的,mayInterruptIfRunning為true時,表明這個任務會被打斷的,並返回true;
    //為false時,會等待這個任務執行完,返回true;若任務還沒執行,取消任務後返回true,如任務執行完,返回false
    boolean cancel(boolean mayInterruptIfRunning);
    //判斷任務是否被取消了,正常執行完不算被取消
    boolean isCancelled();
    //判斷任務是否已經執行完成,任務取消或發生異常也算是完成,返回true
    boolean isDone();
    //獲取任務返回結果,如果任務沒有執行完成則等待完成將結果返回,如果獲取的過程中發生異常就丟擲異常,
    //比如中斷就會丟擲InterruptedException異常等異常
    V get() throws InterruptedException, ExecutionException;
    //在規定的時間如果沒有返回結果就會丟擲TimeoutException異常
    V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
--------------------- 
作者:tangedegushi 
來源:CSDN 
原文:https://blog.csdn.net/tangedegushi/article/details/80002297 
版權宣告:本文為博主原創文章,轉載請附上博文連結!
// Callable 測試用例
public class MyThread3<T> implements Callable {

	@Override
	public T call() throws Exception {
		System.out.println("local logic for Callable test.");
		return null;
	}

	public static void main(String[] args) {
		Callable<Integer> oneCallable = new MyThread3<Integer>();
		FutureTask<Integer> oneTask = new FutureTask<>(oneCallable);
		Thread thread = new Thread(oneTask);
		thread.start();
		
		boolean isDone = oneTask.isDone();
		System.out.println("local logic for Callable test, isDone:" + isDone);
	}
}

4、使用ExecutorService

用ExcecutorService實現執行緒建立(執行緒池),Excecutor以後開章節單獨記。

// 執行緒池測試
public class MyThread4<Integer> implements Callable{

	private Integer num;

	public MyThread4(Integer num) {
		this.num = num;
	}

	@Override
	public Integer call() throws Exception {
		return num;
	}

	public static void main(String[] args) {

		int taskSize = 5;
		ExecutorService pool = Executors.newFixedThreadPool(taskSize);

		// 建立多個有返回值的任務
		List<Future> list = new ArrayList<Future>();
		for(int i = 0; i < taskSize; i++) {
			Callable c = new MyThread4<>(i);
			Future future = pool.submit(c);
			list.add(future);
		}

		pool.shutdown();

		// 獲取所有併發任務的執行結果
		for (Future future : list) {
			try {
				System.out.println("Thread : " + future.get().toString());
			} catch (Exception e) {

			}
		}

	}

}

參考:

https://www.cnblogs.com/felixzh/p/6036074.html

https://blog.csdn.net/tangedegushi/article/details/80002297