これは、実際の解決策というよりもヒントのようなものです。おそらく、独自のニーズに合わせて調整する必要があります。
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();
}