程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#的Task和Java的Future

C#的Task和Java的Future

編輯:C#入門知識

自從項目中語言換成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";             }         });     }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved