【名师课堂】Java高级开发

【名师课堂】Java高级开发

Java核心第三部
156课时 |
31736人已学 |
(17 评论)

加入学习
加入学习

通过Callable实现多线程

public interface Callable<V>{
    public V call() throws Exception;

}

Runnable中的run()方法虽然也是线程的主方法,但并没有返回值

public FutureTask(Callable<V> callable)


class MyThread implements Callable<String>{
    
    private int ticket=10,i=10;
    
    @Override
    public String call() throws Exception {
        while(i-->0 && this.ticket>0){
            System.out.println("Sell tickets:"+this.ticket--);
            }
        return "end";
    }
    
}

public class Test {

    public static void main(String args[]) throws InterruptedException, ExecutionException {
         FutureTask<String> task=new FutureTask<String>(new MyThread());
         new Thread(task).start();;
         System.out.println(task.get());
         
    }
}

这种形式主要是返回结果

[展开全文]

Runnable中的run()方法虽然也是线程的主方法,但是很多时候需要一些返回值,这是需要Callable

[展开全文]

授课教师

阿里云开发者社区全面升级
一站式体验,助力云上开发!
进入新社区

相关课程

查看更多 >

本课程相关云产品