我试图演示一个“随时算法” - 一种可以随时停止并返回其当前结果的算法。演示算法只返回i的一些数学函数,其中i正在增加。它会查看它是否被中断,如果是,则返回当前值:
sudo /opt/bitnami/ctlscript.sh restart apache
在主程序中,我这样使用它:
static int algorithm(int n) {
int bestSoFar = 0;
for (int i=0; i<n; ++i) {
if (Thread.interrupted())
break;
bestSoFar = (int)Math.pow(i, 0.3);
}
return bestSoFar;
}
当我运行此程序时,我得到以下输入:
Runnable task = () -> {
Instant start = Instant.now();
int bestSoFar = algorithm(1000000000);
double durationInMillis = Duration.between(start, Instant.now()).toMillis();
System.out.println("after "+durationInMillis+" ms, the result is "+bestSoFar);
};
Thread t = new Thread(task);
t.start();
Thread.sleep(1);
t.interrupt();
t = new Thread(task);
t.start();
Thread.sleep(10);
t.interrupt();
t = new Thread(task);
t.start();
Thread.sleep(100);
t.interrupt();
t = new Thread(task);
t.start();
Thread.sleep(1000);
t.interrupt();
}
}
即,当我告诉他们时,前三个线程确实被中断,但是最后一个线程在1秒后没有中断 - 它继续工作将近22秒。为什么会这样?
编辑:我使用Future.get获得类似的结果并超时。在这段代码中:
after 0.0 ms, the result is 7
after 10.0 ms, the result is 36
after 100.0 ms, the result is 85
after 21952.0 ms, the result is 501
如果超时最多为800,则一切正常,并打印出类似“806.0 [ms]后的超时”的内容。但如果超时为900,则打印“5084.0 [ms]后的超时”。
编辑2:我的电脑有4个核心。该程序在Open JDK 8上运行。