简体   繁体   English

为什么Java线程wait()仅在这里有时间限制?

[英]Why does java thread wait() work only with time limit in here?

I am trying to get familiar with Java threads for the SCJP and I had a question. 我试图熟悉SCJP的Java线程,但有一个问题。

In the below-written code i simply created: two Runnables with a common data storage (an array) and a synchronized write() method to fill it with data successively leaving a letter as a mark for each Runnable (A and B) in sequence. 在下面编写的代码中,我简单地创建了:两个具有公共数据存储区(数组)的Runnables和一个同步write()方法,用数据依次填充它,并在每个Runnable(A和B)中依次留下一个字母作为标记。

I know the code is rough and could be better written but I was seeking the moral of the threads. 我知道代码很粗糙,可能会写得更好,但是我一直在寻找线程的道义。

So now when I run it, it never terminates and the results stop at: 所以现在当我运行它时,它永不终止,结果停在:

Still good. 还好。 A0. A0。

But when I change wait() to wait(100) it works just fine counting from 0 to 9 and it terminates normally. 但是,当我将wait()更改为wait(100)时,它从0到9的计数很好,并且正常终止。 Could someone explain the reason behind that for me please? 有人可以帮我解释一下原因吗?

Thank you. 谢谢。

public class ArrayThreads {

Object[] array = new Object[10];
boolean isA = true;

    int position = 0;

    int getIndex(){
        return position;
    }



class ThreadA implements Runnable{

            synchronized void write(String value){
                    while(!isA){
            try {
                wait();
            } catch (InterruptedException ex) {
                System.out.println("An error in" + value);
                ex.printStackTrace();
            }
        }
        array[position] = value + position;
        System.out.println(array[position]);
        position++;
        isA = !isA;
        notify();
    }

    public void run() {
        while(getIndex()<array.length){
            if (getIndex()==9) return;
            else
        write("A");}
    }
}

    class ThreadB implements Runnable{

                synchronized void write(String value){
                    while(isA){
            try {
                wait();
            } catch (InterruptedException ex) {
                System.out.println("An error in" + value);
                ex.printStackTrace();
            }
        }
        array[position] = value + position;
        System.out.println(array[position]);
        position++;
        isA = !isA;
        notify();
    }

    public void run() {
        while(getIndex()<array.length){
            if (getIndex()==9) return;
            else
        write("B");}
    }
}

    public static void main(String[] args){
        ArrayThreads threads = new ArrayThreads();
        Thread threadA = new Thread(threads.new ThreadA());
        Thread threadB = new Thread(threads.new ThreadB());
        System.out.println("Still good");

        threadB.start();
        threadA.start();
    }

} }

Your threads are each waiting and notifying separate objects - so they're not communicating with each other at all. 每个线程都在等待并通知单独的对象-因此它们根本没有相互通信。 If you want them to effectively release each other, they'll need a shared monitor to synchronize, wait on and notify. 如果您希望他们有效地互相释放,他们将需要一个共享的监视器来同步,等待并通知。

It's "working" when you specify a timeout because it's effectively turning the wait call into a sleep call... still nothing is really waiting/notifying usefully, because the two threads are still dealing with separate monitors. 当您指定超时时,它是“有效的”,因为它将有效地将等待呼叫转换为睡眠呼叫……实际上,没有任何东西在等待/通知有用,因为两个线程仍在处理单独的监视器。

your objects are not working in same monitor. 您的对象不在同一监视器中工作。

you need to either move the wait() and notify() to same object like: http://www.java-samples.com/showtutorial.php?tutorialid=306 您需要将wait()和notify()移至同一对象,例如: http : //www.java-samples.com/showtutorial.php?tutorialid=306

or you can notify the target object: http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ315_016.htm 或者您可以通知目标对象: http : //www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ315_016.htm

when you set wait(100). 当您设置wait(100)时。 you are setting a timeout. 您正在设置超时。 and definitely it will wake up after 100ms. 肯定会在100毫秒后唤醒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM