通知方法的放置问题

问题描述 投票:0回答:1

我正在尝试等待和通知方法。当放入 run 方法时通知方法不起作用,但当将相同的方法放入其他方法时它可以工作。

public class NewProgram {
static int balance = 0;

public void withdraw(int amount) {
    synchronized(this)
    {
        if(balance== 0) {
        try{
            System.out.println("Waiting for deposit");
            wait();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        }
    }
        balance = balance - amount;
        System.out.println("Amount Withdrawn Successfully");   
}
public void deposit(int amount) {

    balance = balance + amount;
    System.out.println("Money Deposited Successfully");

    //  The Notify method here works
    //    synchronized(this) 
    //         {
    //             notify();
    //         }}

public static void main(String[] args) {

    NewProgram app = new NewProgram();
    Thread thread1 = new Thread (new Runnable(){

        @Override
        public void run(){
            app.withdraw(2000);
        }
    }); 
    
    thread1.start();

    Thread thread2 = new Thread(new Runnable(){

        @Override
        public void run() {
            try {
                Thread.sleep(5000);

            //  The Notify method here doesn't work
            //     synchronized(this) {
            //     notify();
            // }
                
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }
            
            app.deposit(3000);


            // The notify method from here doesn't work
            //synchronized(this) {
            //     notify();
            //}            
            System.out.println("Thread 2 ends");
        } 
    });
    thread2.start();
}}

所以,在这个程序中,当余额为零时,取款方法等待存款方法存入资金。然后等待锁被移除,提现操作继续。当存款方法中调用notify方法时,该程序完美运行。但是当调用deposit方法后将notify放置在线程2的run方法中时,wait上的锁并没有被解除,而是执行了下一条语句Thread 2结束,程序无限期地等待。请帮我解决这个问题。

multithreading wait notify
1个回答
0
投票

当您写下

notify()
时,其含义与您写下 this.notify()
完全
相同。

您的

deposit()
方法是
NewProgram
类的实例方法。当您在 Deposit() 方法中写入
notify()
时,您将通知调用 Deposit() 方法的 NewProgram 实例。在 Deposit() 内部,
this
指的是 NewProgram 实例。

您的 thread2

run()
方法不是 NewProgram 实例方法。它是您在编写 new Runnable(){ ... } 时定义的 anonymous
 类的实例方法。当你在
notify()
方法中写下
run()
时,那就真的是
this.notify()
了,而
this
对象是匿名类的实例,而不是
withdraw()中等待通知的NewProgram实例 方法。

© www.soinside.com 2019 - 2024. All rights reserved.