PART.1 通過Thread實現多線程<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
1. Thread
getID() |
獲取線程ID。 |
getName(), setName() |
獲取和設置線程名。 |
getPriority(), setPriority() |
獲取和設置線程優先級。 |
getState() |
獲取線程狀態。 |
getThreadGroup() |
獲取線程所在的線程組。 |
isAlive() |
獲取線程是否已經啓動並且沒有終止。 |
isDaemon(), setDaemon() |
獲取和設置線程是否爲守護線程。 |
isInterrupted() |
獲取線程是否被中斷。 |
start() |
開始線程。 |
join() |
等待指定線程中終止。 |
interrupt() |
中斷線程 |
靜態方法
currentThread() |
獲取當前線程。 |
sleep() |
使當前線程休眠指定的時間。 |
yield() |
使當前線程暫停執行,讓其它等待的線程執行。 |
interrupted() |
獲取當前線程是否被中斷。 |
2. 通過Thread實現多線程
1. 通過繼承Thread類並覆蓋Thread的run()方法創建一個新的線程類。
2. 使用該線程類創建線程對象。
- public class ThreadTest
- {
- public static void main(String[] args) throws Exception
- {
- TestThread th = new TestThread("thread 1");
- th.start();
- th.join();
- System.out.println("'main' ended.");
- }
- private static class TestThread extends Thread
- {
- public TestThread(String threadName)
- {
- super(threadName);
- }
- @Override
- public void run()
- {
- String thName = Thread.currentThread().getName();
- System.out.printf("'%s' started. /n", thName);
- for (int i = 0; i < 10; i++)
- {
- System.out.println(i);
- }
- System.out.printf("'%s' ended. /n", thName);
- }
- }
- }
3. 通過Runnable實現多線程
1. 創建一個Runnable接口的實現類(實現run()方法)。
2. 通過Thread類包含Runnable的構造方法創建線程對象。
Thread(Runnable target)
Thread(ThreadGroup group, Runnable target)
ThreadGroup group, Runnable target, String name)
- public class RunnableTest
- {
- public static void main(String[] args) throws Exception
- {
- Thread th = new Thread(new TestRunnable(), "thread 1");
- th.start();
- th.join();
- System.out.println("'main' ended.");
- }
- private static class TestRunnable implements Runnable
- {
- @Override
- public void run()
- {
- String thName = Thread.currentThread().getName();
- System.out.printf("'%s' started. /n", thName);
- for (int i = 0; i < 10; i++)
- {
- System.out.println(i);
- }
- System.out.printf("'%s' ended. /n", thName);
- }
- }
- }
4. ThreadGroup
activeCount() |
獲取線程組中正在執行的線程數量。 |
activeGroupCount() |
獲取線程組中正在執行的線程組數量。 |
getMaxPriority(), setMaxPriority() |
獲取和設置最大優先級 |
getName() |
獲取線程組的名稱。 |
getParent() |
獲取父線程組 |
interrupt() |
中斷線程組中的所有線程。 |
isDaemon(), setDaemon() |
獲取和設置線程組是否爲守護線程。 |
parentOf(ThreadGroup) |
判斷線程組是否包含於指定線程組中。 |
5. 通過ThreadGroup管理線程
在創建線程對象時,通過包含ThreadGroup的構造方法創建,將線程加入指定線程組
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, Runnable target, String name)
Thread(ThreadGroup group, String name)
- public class ThreadGroupTest
- {
- public static void main(String[] args) throws Exception
- {
- // 創建線程組對象。
- ThreadGroup tg = new ThreadGroup("group 1");
- // 向線程組中加入10個線程。
- for (int i = 0; i < 10; i++)
- {
- Thread th = new Thread(tg, new TestRunnable(), "thread " + i);
- th.start();
- }
- // 等待2秒。
- Thread.sleep(2000);
- // 中斷所有線程。
- tg.interrupt();
- // 輸出
- System.out.println(tg.activeCount());
- }
- private static class TestRunnable implements Runnable
- {
- @Override
- public void run()
- {
- String thName = Thread.currentThread().getName();
- System.out.printf("'%s' started. /n", thName);
- while (!Thread.currentThread().isInterrupted())
- {
- }
- System.out.printf("'%s' ended. /n", thName);
- }
- }
- }
PART.2 通過Callable和FutureTask實現異步調用
1. Callable<V>
Ø V爲返回值的類型。
Ø 實現Callable接口需實現call方法。
Ø 與Runnable的run方法相比,call方法具有返回值V和異常聲明。
2. FutureTask<V>
V爲返回值得類型。
cancel() |
取消執行。 |
get() |
阻塞獲取執行結果。 |
get(long, TimeUnit) |
指定阻塞的最長時間,獲取執行結果。 |
isCancelled() |
獲取是否被取消。 |
isDone() |
獲取是否完成。 |
run() |
開始執行。 |
3. 通過Callable和FutureTask異步執行
1. 創建一個Callable<V>的實現類。
2. 創建FutureTask<V>對象。
3. 執行創建的FutureTask對象。(run方法)
4. 通過FutureTask對象獲取結果。(get方法)
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
- public class FutureTaskTest
- {
- public static void main(String[] args)
- {
- FutureTask<Integer> ct = null;
- ct = new FutureTask<Integer>(new TestCallable());
- ct.run();
- try
- {
- int ret = ct.get();
- System.out.println(ret);
- }
- catch (InterruptedException e)
- {
- // ct.get() 時線程被中斷。
- e.printStackTrace();
- }
- catch (ExecutionException e)
- {
- // Callable在執行時出現異常。
- e.printStackTrace();
- }
- }
- private static class TestCallable implements Callable<Integer>
- {
- @Override
- public Integer call() throws Exception
- {
- double i = Math.random() * 100;
- return (int)i;
- }
- }
- }
4.處理FutureTask執行時發生的異常
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
- public class FutureTaskExceptionTest
- {
- public static void main(String[] args)
- {
- FutureTask<Integer> ct = null;
- ct = new FutureTask<Integer>(new TestCallable());
- ct.run();
- try
- {
- int ret = ct.get();
- System.out.println(ret);
- }
- catch (InterruptedException e)
- {
- // ct.get() 時線程被中斷。
- e.printStackTrace();
- }
- catch (ExecutionException e)
- {
- // Callable在執行時出現異常。
- System.out.println(e.getCause().getMessage());
- System.out.println(e.getMessage());
- }
- }
- private static class TestCallable implements Callable<Integer>
- {
- @Override
- public Integer call() throws Exception
- {
- throw new Exception("An test exception.");
- }
- }
- }
PART.3 通過ExecutorService實現多線程
1. ExecutorService
awaitTermination |
等待所有任務結束。 |
invokeAll |
執行集合中的所有任務,返回所有Future。該方法將等待所有任務結束或指定的時間。 |
invokeAny |
執行集合中的一個任務,返回該任務得返回值。 |
isShutdown |
獲取ExecutorService是否被shutdown。 |
isTerminated |
獲取是否所有任務已經結束。 |
Shutdown |
等待所有正在執行的任務結束。將沒有執行的任務返回。不執行後新的任務。 |
shutdownNow |
中斷正在執行的任務。返回沒有執行的任務。 |
submit |
提交一個任務並開始執行。 |
2. 創建ExecutorService
Executors.newCachedThreadPool
Executors.newFixedThreadPool
Executors.newScheduledThreadPool
Executors.newSingleThreadExecutor
Executors.newSingleThreadScheduledExecutor
3. 通過ExecutorService實現多線程
1. 創建ExecutorService對象。
2. 向ExecutorServices對象提交任務。
3. 獲得結果。
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- public class ExecutorServiceTest
- {
- public static void main(String[] args) throws Exception
- {
- ExecutorService es = Executors.newCachedThreadPool();
- // 創建10個任務,將這些任務交由ExecutorService執行,保存這些任務的Future到List。
- List<Future<Integer>> fs = new ArrayList<Future<Integer>>(10);
- for (int i = 0; i < 10; i++)
- {
- TestCallable t = new TestCallable();
- Future<Integer> f = es.submit(t);
- fs.add(f);
- }
- // 等待執行結束。
- Thread.sleep(1000);
- // 輸出執行結果。
- for (Future<Integer> f : fs)
- {
- System.out.println(f.get());
- }
- // 關閉ExecutorService。
- es.shutdown();
- }
- private static class TestCallable implements Callable<Integer>
- {
- @Override
- public Integer call() throws Exception
- {
- double ret = Math.random() * 100;
- return (int)ret;
- }
- }
- }
4. 關閉ExecutorService
shutdown() 等待任務結束
shutdownNow() 中斷任務
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class ExecutorServiceShutdownTest
- {
- public static void main(String[] args) throws Exception
- {
- // PART 1 測試shutdownNow()。
- System.out.println("----- PART 1");
- // 創建ExecutorService。
- ExecutorService es = Executors.newCachedThreadPool();
- // 開始10個任務。
- System.out.println("----- Start all tasks...");
- for (int i = 0; i < 10; i++)
- {
- TestCallable task = new TestCallable("task " + i);
- es.submit(task);
- }
- // 等待5秒。在此期間可能有任務結束。
- System.out.println("----- Wait for 5 seconds.");
- Thread.sleep(5000);
- // 結束所有任務。
- System.out.println("----- Shutdown all tasks now.");
- es.shutdownNow();
- System.out.println("----- End of PART 1");
- Thread.sleep(1000);
- // 測試shutdown()。
- System.out.println("----- PART 2");
- Thread.sleep(1000);
- // 創建ExecutorService。
- es = Executors.newCachedThreadPool();
- // 開始10個任務。
- System.out.println("----- Start all tasks...");
- for (int i = 0; i < 10; i++)
- {
- TestCallable task = new TestCallable("task " + i);
- es.submit(task);
- }
- // 等待5秒。在此期間可能有任務結束。
- System.out.println("----- Wait for 5 seconds.");
- Thread.sleep(5000);
- // 結束所有任務。
- System.out.println("----- Shutdown all tasks.");
- es.shutdown();
- System.out.println("----- End of main.");
- }
- private static class TestCallable implements Callable<Void>
- {
- private String name;
- public TestCallable(String name)
- {
- this.name = name;
- }
- @Override
- public Void call() throws Exception
- {
- System.out.printf("'%s' started. /n", name);
- // 等待3 - 12秒。
- try
- {
- int w = (int)(Math.random() * 10 + 3);
- Thread.sleep(w*1000);
- }
- catch (InterruptedException e)
- {
- System.out.printf("'%s' interrupted. /n", name);
- }
- System.out.printf("'%s' ended. /n", name);
- return null;
- }
- }
- }