How to timeout a thread

后端 未结 17 1145
时光说笑
时光说笑 2020-11-22 01:01

I want to run a thread for some fixed amount of time. If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How

17条回答
  •  旧时难觅i
    2020-11-22 01:29

    Now , l meet a issue like this. It happens to decode picture. The process of decode takes too much time that the screen keep black. l add a time controler: when the time is too long, then pop up from the current Thread. The following is the diff:

       ExecutorService executor = Executors.newSingleThreadExecutor();
       Future future = executor.submit(new Callable() {
           @Override
           public Bitmap call() throws Exception {
           Bitmap bitmap = decodeAndScaleBitmapFromStream(context, inputUri);// do some time consuming operation
           return null;
                }
           });
           try {
               Bitmap result = future.get(1, TimeUnit.SECONDS);
           } catch (TimeoutException e){
               future.cancel(true);
           }
           executor.shutdown();
           return (bitmap!= null);
    

提交回复
热议问题