Java JUnit子线程测试IllegalMonitorStateException

时间:2018-12-11 15:21:40

标签: java multithreading testing junit

有没有一种方法可以编写可以在子线程中捕获IllegalMonitorStateException的测试方法,或者应该如何重构代码。同步化的单词被专门删除以获取异常。经过测试的类的代码:

public class Task2v3_withoutSynchro implements Runnable{

    private int val=-1;
    private int oldVal=-2;
    private boolean valueSet=false;
    private boolean isFinished = false;

    @Override
    public void run() {
        new Thread(this::print).start();
        new Thread(this::count).start();
    }

    private void count(){
            for(int i=0; i<1_000_000;i++){
                if(valueSet){
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                val=i;
                valueSet=true;
                notify();
            }
            isFinished=true;
            Thread.currentThread().interrupt();
    }

    private void print(){
        while (!isFinished){
                if(!valueSet){
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                    valueSet=false;
                    oldVal=val;
                    notify();
            }
        Thread.currentThread().interrupt();
    }
}

测试方法的想法

public class Task2 {
    @Test(expected = java.lang.IllegalMonitorStateException.class)
    public void withoutSynchroTest1(){
        new Task2v3_withoutSynchro().run();
    }
}

0 个答案:

没有答案