首页 > 解决方案 > 我怎么知道是谁造成了中断异常?(爪哇)

问题描述

我在我的代码中使用中断()从一个线程向另一个线程发出信号,以从“无休止”(最大时间)睡眠中唤醒并在一段时间内验证一个条件。我也在使用监视器(同步块、通知和等待)和同步方法。我写我的代码的方式是一些线程休眠直到它们得到一个中断,但是一些中断在它们不应该被唤醒时唤醒线程(它们必须模拟它们正在做其他事情睡觉)。问题是我无法找到不应该执行中断()的线程,我怎么能找到它?

以这种方式使用中断()进行编码是一种好方法吗?

那是睡眠被打断但不应该被打断的代码

private void medicalVisit(int number) {
    long sleepTime = (long) ((Math.random() * 2 + 0.5) * 1000); // 500 <= sleepTime (in msec) <= 2500
    try {
        Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
        System.out.println(this.getName()+" ERROR, interrupt from sleep, id: 2 (medicalVisit)");
        e.printStackTrace();
    }
    System.out.println(this.getName()+" - "+number+"° medical visit ended");
}

这是启动中断的代码示例

private void handlerYellowPatient() {
    Iterator<Patient> patientIt = yellows.iterator();
    while(patientIt.hasNext()) {
        Patient p = patientIt.next();
        p.itsTurn = true;
        p.interrupt();
        yellows.remove(p);
    }
}

这是一个正确“消耗”中断的代码示例

private void waitUntilItsTurn(int number) {
    // simulating the period of time before entering in guard
    long sleepTime = (long) ((Math.random() * 2 + 0.5) * 1000); // 500 <= sleepTime (in msec) <= 2500
    try {
        Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
        // must not be awaken while here
        System.out.println(this.getName()+" ERROR MAYBE, interrupt from sleep, id: 1");
        e.printStackTrace();
    }
    WMan.addPatient(this, WMan);
    while (!itsTurn) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            // WMan handlerRedPatient interrupt#1
            System.out.println(this.getName()+" - the wait is over, it's my turn for the "+number+"° times");
        }   
    }
    itsTurn = false;
}

希望这些代码可以提供帮助

标签: javamultithreadingdebuggingsleepinterrupt

解决方案


推荐阅读