【问题标题】:help in synchronized method in javajava中同步方法的帮助
【发布时间】:2023-03-08 02:38:01
【问题描述】:

我用 java 编写了一个程序来模拟生产水的同步(氧气等待氢气可用),但它给出了“意外操作异常”并且没有工作...... 请帮帮我...

有我的代码:

// 线程 Oxygen 的类 公共类 Thread_O 实现 Runnable {

Object object;

public Thread_O(Object o) {

    object = o;
}

public void run() {
    try {

        oxygen();

    } catch (InterruptedException ex) {
        Logger.getLogger(Thread_O.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new UnsupportedOperationException("Not supported yet.");
}

public void oxygen() throws InterruptedException {

    System.out.println("One O2 created...");

    synchronized (object) {

        object.wait();
        object.wait();
    }

    System.out.println("**** H2O created...");

}

}

// 线程氢类 公共类 Thread_H 实现 Runnable {

Object object;

public Thread_H(Object o) {

    object = o;
}

public void run() {
    try {

        Hydrogen();

    } catch (InterruptedException ex) {
        Logger.getLogger(Thread_H.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new UnsupportedOperationException("Not supported yet.");
}

public void Hydrogen() throws InterruptedException {

    System.out.println("One H2 created...");

    synchronized (object) {

        object.notifyAll();
    }
}

}

//在我们的主类中:

Object object = new Object();

//在氧气按钮中:

    Thread thread_O = new Thread(new Thread_O(object));
    thread_O.run();

//在Hydrogen的按钮中:

    Thread thread_H = new Thread(new Thread_H(object));
    thread_H.run();

【问题讨论】:

标签: java multithreading concurrency


【解决方案1】:

顺便说一句,线程从方法start() 没有run() 开始。如果您调用run(),那么您将执行该方法,但在当前线程中没有新线程。

【讨论】:

  • 我知道,这只是小费。我认为你的问题在于抛出异常 no in but after catch 所以你总是抛出它。不过这是别人写的,不想重复了。
【解决方案2】:

您的代码在 Thread_O 类中 run() 方法的最后一行抛出异常。

您需要删除此行。

【讨论】:

    【解决方案3】:

    您的程序在 Thread_H 和 Thread_O run() 方法中抛出异常。您已经提供了 run() 方法的实现,因此请删除引发异常的行。删除这些行。

    throw new UnsupportedOperationException("Not supported yet.");
    

    @Gaim 是正确的,您需要使用 start() 开始执行线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多