你能发现错误吗?这将抛出一个java.lang.OutOfMemoryError
.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestTheads {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
while(true) {
executorService.submit(new Runnable() {
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
});
}
}
}
错误是我调用executorService.submit()
而不是executorService.execute()
,因为submit()
返回一个Future
我忽略的对象。有了execute()
,这个程序实际上将永远运行。
然而,一个人并不总是拥有一种execute()
方法,比如使用 a 时ScheduledExecutorService
:
public static void main(String[] args) {
// this will FAIL because I ignore the ScheduledFuture object
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
while(true) {
executorService.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}, 1, 1, TimeUnit.SECONDS);
}
}
一个不返回任何东西,只计算的任务应该做什么?
任何想法将不胜感激!
编辑:看起来很有希望,但它只会清除已取消ThreadPoolExecutor
的任务。purge()