The following working example prints every 3sec a integer between 1 and 20. The program should terminate if one of the two status flacs (t1.getStatus, t2.getStatus) are true. If t1.getStatus
is true then the program is still running, because the scanner doesn't terminate.
public class Test {
public static void main(String[] args) {
FirstTask t1 = new FirstTask();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(t1, 0, 3, TimeUnit.SECONDS);
ParallelScanner t2 = new ParallelScanner();
Thread scan = new Thread(t2);
scan.start();
while(true){
if(t1.getStatus() || t2.getStatus()) break;
}
scan.interrupt();
executor.shutdown();
}
}
class ParallelScanner implements Runnable {
private volatile boolean status=false;
public void run() {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println("scanner stoped");
scan.close();
this.status=true;
}
public boolean getStatus(){
return this.status;
}
}
class FirstTask implements Runnable {
private volatile boolean status=false;
public void run() {
this.status = status();
}
private boolean status() {
int incident = (int) ((Math.random()*20)+1);
System.out.println(incident);
return incident < 7 ? true : false;
}
public boolean getStatus() {
return this.status;
}
}
To control the interrupt via status flac could be also the wrong scratch. I also found a similar question here. Till now the first answer doesn't grab me. And the second answer is wrong. Could someone provide a small working example on this approach? Are there some other alternatives?