用两个线程打印偶数和奇数

时间:2018-05-07 18:44:21

标签: multithreading

我正在尝试使用两个不同的线程打印偶数和奇数但是它正在抛出IllegalMonitorStateException。请告诉我我做错了什么。

包com.rishi.threading;

公共类MyThread {

public static class EvenThread extends Thread {
    Boolean evenFlag;
    Integer sharedCount;

    public EvenThread(Boolean flag, Integer count) {
        this.evenFlag = flag;
        this.sharedCount = count;
    }

    public void run() {

        printEven();

    }

    private void printEven() {

        for (int i = 0; i < 10; i++) {
            synchronized (evenFlag) {
                if (!evenFlag) {
                    try {
                        evenFlag.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                evenFlag = false;
                System.out.println("even thread :" + sharedCount++);
                notifyAll();
            }
        }
    }
}

public static class OddThread extends Thread {
    Boolean evenflag;
    Integer sharedCount;

    public OddThread(Boolean flag, Integer count) {
        this.evenflag = flag;
        this.sharedCount = count;
    }

    public void run() {

        printOdd();
    }

    private void printOdd() {
        // TODO Auto-generated method stub

        for (int i = 0; i < 10; i++) {
            synchronized (evenflag) {
                if (evenflag) {
                    try {
                        evenflag.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                evenflag = true;
                System.out.println("odd thread :" + sharedCount++);
                notifyAll();
            }
        }
    }
}

public static void main(String[] args) {
    Boolean evenFlag = new Boolean(true);
    Integer sharedCount = new Integer(0);
    EvenThread thread1 = new EvenThread(evenFlag, sharedCount);
    thread1.setName("evenThread");
    OddThread thread2 = new OddThread(evenFlag, sharedCount);
    thread2.setName("oddthread");
    thread1.start();
    thread2.start();
}

}

我创建了两个线程“EvenThread”和“OddThread”。 这两个线程共享两个公共成员变量,即evenFlag和sharedCount。 evenFlag - &gt;只是一个标志,当sharedCount为偶数时设置为true,当shareDcount设置为奇数时设置为false。 所以这个线程都试图锁定evenFlag以控制sharedCount的打印。

0 个答案:

没有答案