java多線程四種實現方法
阿新 • • 發佈:2019-02-21
pub 主線程 通過 edt dex over main java nds
package com.zrun.TestThread; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class App { public static void main(String[] args) throws Exception, ExecutionException { System.out.println("主線程啟動:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date())); // 方式1 // ThreadEx thread1 = new ThreadEx(); // thread1.start(); // Thread.sleep(2000); // System.out.println("主線程執行結束:" // + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // .format(new Date())); // 方式2 // Thread thread2 = new Thread(new RunableEx()); // thread2.start(); // Thread.sleep(2000); // System.out.println("主線程執行結束:" // + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // .format(new Date())); // 方式3 // Callable<Object> oneCallable = new Thread3<Object>(); // FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable); // Thread t = new Thread(oneTask); // t.start(); // Thread.sleep(2000); // System.out.println("主線程執行結束:" // + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // .format(new Date())); // // 主線程執行的2秒鐘之後,子線程只要再過3秒就結束了,從而得到子線程的結果;這裏get方法會阻塞主線程 // System.out.println(oneTask.get().toString()); // 方式4 Thread4.test(); Thread.sleep(2000); System.out.println("主線程執行結束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date())); } } // 方式1:繼承Thread類 class ThreadEx extends Thread { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子線程執行結束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date())); } } // 方式2:實現Runnable接口 class RunableEx implements Runnable { public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子線程執行結束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date())); } } // 方式3:通過Callable和FutureTask;這種方式可以拿到子線程的返回值 class Thread3<Object> implements Callable<Object> { @Override public Object call() throws Exception { Thread.sleep(5000); return (Object) ("我是子線程的返回值:" + new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(new Date())); } } // 方式4:通過線程池創建線程 class Thread4 { static int POOL_NUM = 5; public static void test() { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < POOL_NUM; i++) { RunableEx thread = new RunableEx(); executorService.execute(thread); } // 關閉線程池 executorService.shutdown(); } }
java多線程四種實現方法