標籤:ring 四種 read res adp over 執行 print 擷取
java多線程的實現可以通過以下四種方式
1.繼承Thread類,重寫run方法
2.實現Runnable介面,重寫run方法
3.通過Callable和FutureTask建立線程
4.通過線程池建立線程
方式1,2不再贅述.
方式3,通過Callable和FutureTask建立線程實現多線程
@Test public void MyCallableTest() throws Exception { //建立線程執行對象 MyCallable myCallable = new MyCallable(); FutureTask<String> futureTask = new FutureTask<>(myCallable); //執行線程 Thread thread = new Thread(futureTask); thread.start(); //擷取線程方法返回資料 System.out.println(futureTask.get()); } /** * 建立實作類別 */ class MyCallable implements Callable<String>{ @Override public String call() throws Exception { System.out.println("test thread by callable"); return "result"; } }
方式4,通過線程池建立線程
public class ThreadPoolStu { @Test public void TestThreadPool1() throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newFixedThreadPool(2); //執行Runnable介面實作類別 方式1 MyRunnable runnable1 = new MyRunnable(); executorService.execute(runnable1); //執行Runnable介面實作類別 方式2 MyRunnable runnable2 = new MyRunnable(); Future<?> future2 = executorService.submit(runnable2); System.out.println(future2.get());//若未執行完會阻塞該線程 //執行Callable介面實作類別 MyCallable callable3 = new MyCallable(); Future<String> future3 = executorService.submit(callable3); System.out.println(future3.get());//若未執行完會阻塞該線程 // 關閉線程池 executorService.shutdown(); }}class MyCallable implements Callable<String>{ @Override public String call() throws Exception { System.out.println("test thread by callable"); return "result"; }}class MyRunnable implements Runnable { @Override public void run() { System.out.println("thread execute"); }}
java線程實現的四種方式