有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java关于线程等待/通知

我是java线程概念的初学者。我通过实现等待和通知机制做了一个小程序,编码如下:-

例如。爪哇

import comp.samplecheck;

public class Example extends Thread {
public static void main(String[] args) {
    samplecheck sample = new samplecheck("First");
    samplecheck sample1 = new samplecheck("Second");
    samplecheck sample2 = new samplecheck("Third");
    samplecheck sample4 = new samplecheck("Fourth");
    samplecheck sample5 = new samplecheck("Fifth");

    sample.initiate(sample);
    sample1.initiate(sample1);
    sample2.initiate(sample2);

    try {
        Thread.sleep(1000);
        sample4.samplefunc(sample4);
    }
    catch(InterruptedException e) {
        System.out.println("Exception "+e);
    }
}
}

抽样检查。爪哇

package comp;

import java.util.List;
import java.util.ArrayList;

public class samplecheck extends Thread {
String get_text;
samplecheck objs;
static List arr = new ArrayList();

public samplecheck(String str) {
    this.get_text = str;
}

public void run() {     
    synchronized(arr) {
        System.out.println(objs.getName()+" Started Processing");

        try {
            arr.wait();
        }
        catch(InterruptedException e) {
            System.out.println("Exception "+e);
        }

        System.out.println("Initial Array Elements Size "+arr.size());
        for(int i=0; i<100 ; i++){
            arr.add(i);
        }

        System.out.println("After Array Elements Size "+arr.size());
        System.out.println("An Object Is Notified");            
    }
}

public void initiate(samplecheck obj) {
    objs = obj;
    objs.start();
}

public void samplefunc(samplecheck obj) {
    objs = obj;

    synchronized(arr) {
        System.out.println("Notification Process");
        System.out.println("After Array Elements Size "+arr.size());
        arr.notify();
    }
}   
}

在samplecheck中的samplefunc函数中。java如果我给出arr.notify(),我就能够得到正确的输出

    Thread-0 Started Processing
    Thread-1 Started Processing
    Thread-2 Started Processing
    Notification Process
    After Array Elements Size 0
    Initial Array Elements Size 0
    After Array Elements Size 100
    An Object Is Notified

但是如果arr.notifyAll()而不是arr.notify(),则输出为

    Thread-0 Started Processing
    Thread-2 Started Processing
    Thread-1 Started Processing
    Notification Process
    After Array Elements Size 0
    Initial Array Elements Size 0
    After Array Elements Size 100
    An Object Is Notified
    Initial Array Elements Size 100
    After Array Elements Size 200
    An Object Is Notified
    Initial Array Elements Size 200
    After Array Elements Size 300
    An Object Is Notified

但是根据编码透视图,即使我给notifyAll,只有一个获得数组“arr”锁定的对象应该被执行,并在数组中添加元素,并且应该显示通知消息(即)一个对象被通知。但在这里,所有三个对象(即sample、sample1、sample2)都会收到通知并在数组中添加元素。我不知道它为什么以这种方式执行。如果我调用了notifyAll方法三次,那么输出应该与上面的格式相同。我希望输出与前一种情况相同(使用arr.notify()方法获得的输出)

在这个问题上谁能帮我一下


共 (1) 个答案

  1. # 1 楼答案

    第二个输出是正确的。你对这件事的理解是错误的

    3个对象正在等待arr,而不仅仅是一个。我认为这解释了调用notifyAll时的输出

    你可能会问这是从哪里来的

    在每个示例、sample1、sample2线程中,arr上都有一个同步块获取锁。所以这个块一次只能执行一次,这是您在获取锁时所期望的。但是当你调用waitarr上的锁就被释放了。所以在sample-1释放锁后,sample-2进入同步块

    wait文档中:

    This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

    • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
    • Some other thread invokes the notifyAll method for this object.
    • Some other thread interrupts thread T.
    • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

    The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.