重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
创建java线程,我们经常使用两种方式:
创新互联建站是专业的胶州网站建设公司,胶州接单;提供成都网站设计、网站制作,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行胶州网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
但这两种方式有一个缺陷:在执行完任务之后无法直接获取执行结果。
public interface Callable {
V call() throws Exception;
}
public interface Runnable {
public abstract void run();
}
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
public class FutureTask implements RunnableFuture
public interface RunnableFuture extends Runnable, Future {
void run();
}
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("线程执行中...");
}
};
Thread thread = new Thread(runnable);
thread.start();
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("线程执行中...");
return 100;
}
};
FutureTask < Integer > futureTask = new FutureTask < Integer > (callable);
new Thread(futureTask).start();
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("获取执行结果:" + futureTask.get());
}
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("线程执行中...");
return 100;
}
};
ExecutorService service = Executors.newCachedThreadPool();
Future < Integer > future = service.submit(callable);
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("获取执行结果:" + future.get());
}