这更像是一个提示而不是真正的解决方案,您可能需要根据自己的需要对其进行调整。
class MyRunnable implements Runnable{
private String result = "";
private volatile boolean done = false;
public synchronized void run(){
while(!done){
try{
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
result = result + "A";
}
}
public synchronized String getResult(){
return result;
}
public void done(){
done = true;
}
}
以及运行它的代码:
public static void main(String[] args) throws Exception {
MyRunnable myRunnable = new MyRunnable();
ExecutorService service = Executors.newFixedThreadPool(1);
service.submit(myRunnable);
boolean isFinished = service.awaitTermination(5, TimeUnit.SECONDS);
if(!isFinished) {
myRunnable.done();
String result = myRunnable.getResult();
System.out.println(result);
}
service.shutdown();
}