为什么线程不在同步块中等待?

时间:2019-05-01 17:37:13

标签: java multithreading wait notify synchronisation

我正在尝试对较大课程的一小部分进行建模,其中一个线程等待服务器的响应,并且仅在通知线程后才允许方法的返回值。但是,从控制台来看,似乎这不是线程通信的工作方式。我希望线程保持互斥锁直到被通知,因此getValid方法仅在通知该线程后才返回值,但是使用我的代码,我得到了非法的监视器状态异常。我曾尝试研究线程通信的工作方式,但我不太了解它,我认为使用wait方法会使该线程的代码流在该行停止,直到被通知为止,否则不是吗?如果有人有任何建议,将不胜感激。

console contents:

Thread one beginning 5 second sleep...
Exception in thread "Thread-1" Thread two commencing wait...
Thread two getValid method gained mutex lock
true
     

java.lang.IllegalMonitorStateException,位于java.lang.Object.wait(本机方法),位于   ThreadTwo.run(Main.java:80)上的java.lang.Object.wait(Object.java:502)     在java.lang.Thread.run(Thread.java:748)       线程“ Thread-0”中的异常java.lang.IllegalMonitorStateException位于   ThreadOne.run(Main.java:56)上的java.lang.Object.notify(本机方法)     在java.lang.Thread.run(Thread.java:748)

public class Main {

private ThreadOne one;
private ThreadTwo two;

public static void main(String[] args) {

    Main m = new Main();

}

public Main() {

    two = new ThreadTwo();
    one = new ThreadOne(two);

    Thread t1 = new Thread(one);
    Thread t2 = new Thread(two);
    t1.start();
    t2.start();

    System.out.println(isLoginValid());

}


public boolean isLoginValid() {

    return two.getValid();

}

}

class ThreadOne implements Runnable {

private ThreadTwo two;

public ThreadOne(ThreadTwo two) {

    this.two = two;

}

public void run() {

    System.out.println("Thread one beginning 5 second sleep...");

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    two.notify();

}

}

class ThreadTwo implements Runnable {

private Object lock;

public ThreadTwo() {

    lock = new Object();

}

public void run() {

    synchronized(lock) {

        System.out.println("Thread two commencing wait...");

        try {

            this.wait();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("Thread two finished waiting");

    }

}

public boolean getValid() {

    synchronized(lock) {

        System.out.println("Thread two getValid method gained mutex lock");

        return true;

    }

}

}

0 个答案:

没有答案