スレッド実行設定タイムアウト時間

1409 ワード

import java.util.concurrent.*;

/**
 *   ,  ……
 *                
 */
public class Main2 {

    //      ,         : https://blog.csdn.net/LLLLLiSHI/article/details/88057655
    private static ExecutorService pool = Executors.newFixedThreadPool(1);

    /**
     *  jdk api:Future        api
     */
    public static void main(String[] args) {
        System.out.println("       ……");
        //    
        Callable call = new Callable(){
            @Override
            public String call() throws Exception {
                //   2   
                TimeUnit.SECONDS.sleep(2);
                return "        ……";
            }
        };

        //       
        Future result = pool.submit(call);
        try {
            //         ,      :   TimeoutException  
            Object callResult = result.get(1, TimeUnit.SECONDS);
            System.out.println(callResult);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException  ");
        } catch (ExecutionException e) {
            System.out.println("ExecutionException  ");
        } catch (TimeoutException e) {
            System.out.println("TimeoutException  ,         ");
        }
        System.out.println("       ……");
    }

}


 
リファレンスhttps://blog.csdn.net/a9529lty/article/details/42711029