自從項目中語言換成Java後就很久沒有看C#了,但說實話我是身在曹營心在漢啊。早就知道.NET4.5新增了async和await但一直沒有用過,今天看到這篇文章總算有了點了解,突然發現Task這個玩意不就是Java中Future這個概念嗎? 這裡冒昧引用下Jesse Liu文中的C#代碼: static void Main(string[] args) { Console.WriteLine("Main Thread Id: {0}\r\n", Thread.CurrentThread.ManagedThreadId); Test(); Console.ReadLine(); } static async Task Test() { Console.WriteLine("Before calling GetName, Thread Id: {0}\r\n", Thread.CurrentThread.ManagedThreadId); var name = GetName(); Console.WriteLine("End calling GetName.\r\n"); Console.WriteLine("Get result from GetName: {0}", await name); } static async Task GetName() { // 這裡還是主線程 Console.WriteLine("Before calling Task.Run, current thread Id is: {0}", Thread.CurrentThread.ManagedThreadId); return await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("'GetName' Thread Id: {0}", Thread.CurrentThread.ManagedThreadId); return "zhanjindong"; }); } 大家看下"等價"的Java代碼是不是“一模一樣”? static ExecutorService service = Executors.newFixedThreadPool(10); /** * @param args * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, ExecutionException { System.out.println("Main Thread Id: " + Thread.currentThread().getId()); test(); } static void test() throws InterruptedException, ExecutionException{ System.out.println("Before calling getName, Thread Id: "+Thread.currentThread().getId()); Future name = getName(); System.out.println("End calling getName."); System.out.println("Get result from getName: " + name.get()); } static Future getName(){ System.out.println("Before calling ExecutorService.submit, current thread Id is: "+Thread.currentThread().getId()); return service.submit(new Callable() { @Override public String call() throws Exception { Thread.sleep(5000); System.out.println("'getName' Thread Id: "+Thread.currentThread().getId()); return "zhanjindong"; } }); }