java - 在notifyAll()之后线程没有被唤醒;

标签 java multithreading

好的,所以我有这些扩展 Thread 的类,我应该做的是:

  1. 让所有校友都到齐。
  2. 当校友到达时,他们会说“嗨”。
  3. 如果老师到达但并非所有校友都到达,那么他应该 wait() 等待他们。
  4. 校友到齐后应通知老师。

alumn 是一个用 boolean 值 0 初始化的线程。

教师是一个用 boolean 值 1 初始化的线程。

人员/问候语代码

    public class Person extends Thread {
    private Thread t;
    private String threadName;
    boolean id;
    Greeting greeting;
    public Person(String name,boolean tipo,int n){
        this.threadName = name;
        this.id=tipo;  
        greeting =new Greeting();
    }

    @Override
    public void run() {
        if(id==false) { 
            try {
                greeting.alumn(threadName);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        else{
            try {
                greeting.teacher(threadName);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        }
    public void start() 
  {
    System.out.println("Starting "+ threadName);
    if(t==null)
    {
      t=new Thread(this,threadName);
      t.start();
    }
  }
}

class Greeting {

    public void alumn(String s) throws InterruptedException{
        System.out.println(s);
       synchronized (this){
            System.out.println("Alumn: "+s);
            notifyAll();       
    }
    }

    public synchronized void teacher(String s) throws InterruptedException {
        wait();
        System.out.println(s);
    }
}

主类

public class ClassRoom {
    public static void main(String [] args) {

        Person francisco = new Person("Francisco",false,1);
        Person jesus = new Person("Jesus", false,2);
        Person alberto = new Person("Alberto",false,3);
        Person karla = new Person("Karla",false,4);
        Person maestro = new Person("Professor",true,0);
        francisco.start();
        jesus.start();
        alberto.start();
        karla.start();
        maestro.start();
    }
}

问题: 如果老师先到,他就会去 wait()...然后校友到达,但他永远不会醒来。 如果老师不先到,他就永远不会醒来! 如何解决这个问题?

最佳答案

If the teacher arrives first he goes to wait()...then alumns arrive but he never wakes up.

所有的人都实例化他们自己的问候语,它在this上同步,因此也在this上等待/通知。每个人都使用自己的信号量,这不是您想要的。您应该在所有实例的同一个对象(可能是 Greeting.class)上进行同步。

If the teacher doesn't arrive first, he still never wakes up! How to fix this?

只需检查所有校友是否都在那里。如果是打招呼,否则等待通知。之后再检查一下。检查必须是同步块(synchronized block)的一部分,以避免竞争条件。

关于java - 在notifyAll()之后线程没有被唤醒;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22827114/

相关文章:

java - 在 .xml.scala 模板中将 Scala 字符串转换为 Xml

multithreading - 超时后如何正确取消 LoadAsync

java - SimpleDateFormat 更改日期,同时将其转换为不同的日期格式

java - 错误 java.lang.NoClassDefFoundError : com/mongodb/MongoClient

java - Spring webflux 中处理条件响应的正确方法是什么

java - 如何使用java验证带有dtd的xml?

multithreading - julia: 可以玩多线程吗

java - 带 3 个线程的锁

Java无限线程在一段时间后停止

android - 异步任务方法调用在 android 中非常慢