Can I use Callable threads without ExecutorService?

后端 未结 4 1848
花落未央
花落未央 2021-02-02 11:00

Can I use Callable threads without ExecutorService? We can use instances of Runnable and subclasses of Thread without ExecutorService and this code works normally. But this code

4条回答
  •  -上瘾入骨i
    2021-02-02 11:41

    import java.util.concurrent.Callable;
    import java.util.concurrent.FutureTask;
    
    public class MainClass {
        public static void main(String[] args) {
            try {
                Callable c = () -> {
                    System.out.println(Thread.currentThread().getName());
                    return "true";
                };
                FutureTask ft = new FutureTask(c);
                Thread t = new Thread(ft);
                t.start();
    
                String result = ft.get();
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /*
       Output: 
       Thread-0 
       true
     */
    

提交回复
热议问题