简体   繁体   English

用wait,notify和notifyAll替换Await,Signal,SignalAll

[英]Replace Await, Signal, SignalAll with wait,notify and notifyAll

I want to replace await(),signalAll() with wait(),notifyAll() (java's default monitor) and my code listed below, the problem is that once thread get into waiting state. 我想用wait(),notifyAll()(java的默认监视器)和下面列出的代码替换await(),signalAll()和问题,问题是线程一旦进入等待状态。 it never be notified again.. Thanks for your help. 永远不会再收到通知。。谢谢您的帮助。

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AccountThreadCommunicationDefault {
    private static Account account = new Account();
    private static Random random = new Random();
    public static void main(String... args) {
        ExecutorService es = Executors.newFixedThreadPool(2);
        es.execute(new WithdrawTask());
        es.execute(new DepositTask());
        es.shutdown();
    }

    private static class WithdrawTask implements Runnable {
        public void run() {
            while (true) {
                account.withdraw(random.nextInt(600));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }

    private static class DepositTask implements Runnable {
        public void run() {
            while (true) {
                account.deposit(random.nextInt(500));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    private static class Account {
        private Integer balance = 500;
        private static Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        // private Object object = new Object();

        // public synchronized void deposit(int count) {
        public void deposit(int count) {
            try {
                lock.lock();
                System.out.print("当前账户余额:" + balance);
                balance += count;
                System.out.println(" 存款:" + count + " 账户余额(deposit): "
                        + getBalance());
                // synchronized (object) {
                // object.notifyAll();
                // }
                synchronized (this) {
                    this.notify();
                }
            } catch (IllegalMonitorStateException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }

        public void withdraw(int count) {
            try {
                lock.lock();
                while (balance < count) {

                    System.out.println("余额不足:" + getBalance() + " 等待存款..");
                    // synchronized (object) {
                    // object.wait();
                    // }
                    synchronized (this) {
                        this.wait();
                    }

                    System.out.print("当前账户余额:" + balance);
                    balance -= count;
                    System.out.println(" 取现:" + count + " 账户余额(withdraw): "
                            + getBalance());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }

        public int getBalance() {
            return this.balance;
        }
    }

}

You have a deadlock. 你陷入僵局。 The Withdraw task is waiting on the Account object's monitor, while holding the ReentrantLock locked. 提现任务正在等待帐户对象的监视器,同时保持ReentrantLock锁定。 The Deposit task can not notify() the Account object monitor because it can't lock the ReentrantLock. 存款任务无法通知()帐户对象监视器,因为它无法锁定ReentrantLock。

You need to wait() and notify() the same object that you are using as a mutex. 您需要wait()和notify()用作互斥对象的对象。 Doesn't matter whether it's the ReentrantLock or the Account object's monitor. 不管是ReentrantLock还是Account对象的监视器。 But it won't work the way you wrote it with two different locks. 但是它不能像您用两个不同的锁编写它那样工作。

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

相关问题 Java 中的线程 | 等待(),通知()和通知所有() - Threads in Java | wait(), notify() and notifyAll() 使用tryLock()以及wait()和notify()/ notifyAll() - using tryLock() together with wait() and notify()/notifyAll() 为什么等待,通知和notifyAll方法都在Object Class中? - Why wait ,notify and notifyAll Methods are in Object Class? 为什么等待/通知/通知所有方法在 java 中不同步? - why wait/notify/notifyAll methods are not synchronized in java ? 在synchronized语句中的wait(),notify()和notifyAll() - wait(), notify() and notifyAll() inside synchronized statement Condition接口中的signalAll与对象中的notifyAll - signalAll in Condition interface vs notifyAll in object 调用wait(),notify()或notifyAll()时如何获得相同的监视器? - how to get same monitor when calling wait() ,notify() or notifyAll()? notify和notifyall显示奇怪的行为以等待多个线程 - notify and notifyall showing weird behavior to wait of multiple threads 它们是wait()、notify()、lock()、unlock()、await()、signal()、acquire()和release()之间的线程安全方法 - which are thread-safe methods among wait(), notify(), lock(), unlock(), await(), signal(), acquire() and release() ruby线程编程,ruby相当于java wait / notify / notifyAll - ruby thread programming , ruby equivalent of java wait/notify/notifyAll
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM