在Java中,Executor框架提供了一种将任务提交给线程池执行的方式。以下是使用Executor执行器提交任务的几种常见方法:
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("Task is running on thread " + Thread.currentThread().getName());
}
});
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task is running on thread " + Thread.currentThread().getName());
return 42;
}
});
try {
// 获取任务结果,如果任务未完成,get() 方法将阻塞直到完成
Integer result = future.get();
System.out.println("Task returned: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(new Runnable() {
@Override
public void run() {
System.out.println("Task is running on thread " + Thread.currentThread().getName());
}
}, 42);
try {
// 获取任务结果,如果任务未完成,get() 方法将阻塞直到完成
Integer result = future.get();
System.out.println("Task returned: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
ExecutorService executor = Executors.newFixedThreadPool(4);
List<Callable<Integer>> tasks = new ArrayList<>();
tasks.add(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task 1 is running on thread " + Thread.currentThread().getName());
return 42;
}
});
tasks.add(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task 2 is running on thread " + Thread.currentThread().getName());
return 24;
}
});
try {
List<Future<Integer>> futures = executor.invokeAll(tasks);
for (Future<Integer> future : futures) {
System.out.println("Task returned: " + future.get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
ExecutorService executor = Executors.newFixedThreadPool(4);
List<Callable<Integer>> tasks = new ArrayList<>();
tasks.add(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task 1 is running on thread " + Thread.currentThread().getName());
return 42;
}
});
tasks.add(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task 2 is running on thread " + Thread.currentThread().getName());
throw new RuntimeException("Task 2 failed");
}
});
try {
Integer result = executor.invokeAny(tasks);
System.out.println("Task returned: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
在使用完ExecutorService后,应该调用shutdown()或shutdownNow()方法来关闭执行器,以避免资源泄漏。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。