Java Runnable convert to Callable Test

package com.jiangyu;
 
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 
public class TestConvertThread {
  public static final Random r = new Random();
 
  class Call implements Callable<Object> {
 
    @Override
    public Object call() throws Exception {
      Thread.sleep(r.nextInt(5)*1000);
      System.out.println("finished callable");
      return true;
    }
 
  }
 
  class Run implements Runnable {
 
    @Override
    public void run() {
      try {
        Thread.sleep(r.nextInt(5)*1000);
        System.out.println("finished runnable");
      } catch (InterruptedException e) {
      }
    }
 
  }
 
  public void startJob() throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newCachedThreadPool();
    Future<Object> result = null;
    // this is for callable
    result = executor.submit(new Call());
    result.get(10, TimeUnit.SECONDS);
 
    // this is for runnable convert to callable
    result = executor.submit(Executors.callable(new Run()));
    result.get(10, TimeUnit.SECONDS);
  }
 
  public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
    TestConvertThread tt = new TestConvertThread();
    tt.startJob();
  }
}

测试了一下Runnable convert 到 Callable,需要Future返回类型为Object。JDK中可以使用Executors的Callable方法将Runnalbe直接转化为Callable。

Print Friendly

zm

Leave a Reply