通过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