Java Thread系列(一)線程創建
阿新 • • 發佈:2018-05-07
nds list www imp tor 所有 clas HR dex
Java Thread系列(一)線程創建
Java 中創建線程主要有三種方式:繼承 Thread、實現 Runnable 接口、使用 ExecutorService、Callable、Future 實現由返回結果的多線程。
一、繼承 Thread 類創建線程類
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("線程一" + i);
}
}
public static void main(String[] args) {
MyThread th = new MyThread();
th.start();
}
}
註意:通過 start() 方法才能啟動的線程,直接調用的 run() 方法只是普通的方法。
二、實現 Runnable 接口創建線程
public class MyRunnable implements Runnable {
public String ThreadName;
public MyRunnable(String tName){
ThreadName = tName;
}
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(ThreadName);
}
}
public static void main(String[] args) {
MyRunnable th1 = new MyRunnable("線程A");
MyRunnable th2 = new MyRunnable("線程B");
Thread myth1 = new Thread(th1);
Thread myth2 = new Thread(th2);
myth1.start();
myth2.start();
}
}
總結:使用 Runnable 接口創建線程有兩個不足,一是不能同步返回線程執行的結果,二是 run() 方法不能拋出異常。下面介紹 Callable 接口解決這個問題。
三、使用 ExecutorService、Callable、Future 實現由返回結果的多線程
/**
* 有返回值的線程
*/
@SuppressWarnings("unchecked")
class Test {
public static void main(String[] args) throws ExecutionException,
InterruptedException {
System.out.println("----程序開始運行----");
Date date1 = new Date();
int taskSize = 5;
// 創建一個線程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 創建多個有返回值的任務
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable(i + " ");
// 執行任務並獲取Future對象
Future f = pool.submit(c);
// System.out.println(">>>" + f.get().toString());
list.add(f);
}
// 關閉線程池
pool.shutdown();
// 獲取所有並發任務的運行結果
for (Future f : list) {
// 從Future對象上獲取任務的返回值,並輸出到控制臺
System.out.println(">>>" + f.get().toString());
}
}
}
class MyCallable implements Callable<Object> {
private String taskNum;
MyCallable(String taskNum) {
this.taskNum = taskNum;
}
public Object call() throws Exception {
Thread.sleep(1000);
return taskNum;
}
}
《40個Java多線程問題總結》:http://www.importnew.com/18459.html
每天用心記錄一點點。內容也許不重要,但習慣很重要!
Java Thread系列(一)線程創建