中断扫描程序取决于其他线程

时间:2017-02-18 23:01:43

标签: java multithreading

以下工作示例每隔3秒打印1到20之间的一个整数。如果两个状态flacs(t1.getStatus,t2.getStatus)中的一个为真,程序应该终止。如果t1.getStatus为真,则程序仍在运行,因为扫描程序不会终止。

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;
    }

}

通过状态flac控制中断也可能是错误的划痕。我也发现了一个类似的问题here。直到现在,第一个答案并没有抓住我。第二个答案是错误的。有人能为这种方法提供一个小例子吗?还有其他选择吗?

1 个答案:

答案 0 :(得分:0)

我想你知道你的FirstTask只运行一次,所以没关系。

你需要让你的状态变量volatile让每个线程从ram中读取它,否则你会得到一些未定义的行为。

为什么没有使用扫描仪的循环?我不知道你的Scanner类的细节,当没有更多数据时是否抛出异常,或者我的代码假定返回null?

for(;;){
    String input = scan.nextLine();
    if(input == null)
         break;
    // Assuming that by jump over (run through) you mean:
    // ignore the line that comes from the scanner
    if(!t1.getStatus()){
        System.out.println(input); 
    }
}

你的getStatus()方法也需要将状态重置为true,否则它也会忽略(=不打印)所有连续行。