欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Callable 博客分类: 基础知识 java

程序员文章站 2024-03-05 21:56:49
...

  1 import java.lang.Thread;
  2 import java.util.concurrent.Callable;
  3 import java.util.concurrent.Future;
  4 import java.util.concurrent.Executors;
  5 import java.util.concurrent.ExecutorService;
  6 import java.util.concurrent.ExecutionException;
  7
  8 class runclass implements Callable<String> {
  9     private long id = 0;
 10     public runclass(long id){
 11         this.id = id;
 12     }
 13    
 14     @Override
 15     public String call(){
 16         return "id = " + id;
 17     }  
 18 }
 19
 20 class test {
 21     public static void main(String[] args) throws InterruptedException, ExecutionException {
 22         ExecutorService exec = Executors.newCachedThreadPool();
 23         Future<String> result = exec.submit(new runclass(1L));
 24         while (true){
 25             Thread.sleep(1000);
 26             if (result.isDone()){
 27                 System.out.println(result.get());
 28                 break;
 29             }  
 30         }  
 31         exec.shutdown();
 32     }  
 33 }  

相关标签: java