简体   繁体   English

调用wait(),notify()或notifyAll()时如何获得相同的监视器?

[英]how to get same monitor when calling wait() ,notify() or notifyAll()?

main thread creating two thread t1 and t2 run() method of these thread creating two new thread c1 and c2.I want a scenario such that until c1&c2(of t1) are alive t2 will not start executing. 主线程创建两个线程t1和t2,这些线程的run()方法创建两个新线程c1和c2。我想要一个方案,直到t1的c1&c2处于活动状态,t2才会开始执行。 In my code notify and wait are causing Runtime Exception.Since they are not in synchronised block, how to do this? 在我的代码中,notify和wait导致运行时异常。由于它们不在同步块中,该怎么办?

public class childTcreat2newthread {

    public static void main(String[] args) throws InterruptedException {
        Thread mainT = Thread.currentThread();
        Target ra = new Target("a");
        Thread t1 = new Thread(ra);
        t1.start();
        t1.join();

        while (ra.getC1().isAlive() == true || ra.getC2().isAlive() == true) {
            synchronized (mainT) {
                mainT.wait();
            }
        }
        new Thread(new Target("b")).start();
    }
}

class Target implements Runnable {
    Thread c1 = new Thread(new Target1("1"));

    Thread c2 = new Thread(new Target1("2"));
    String msg;

    Target(String msg) {
        this.msg = msg;
    }

    @Override
    public void run() {

        for (int j = 0; j < 100000; j++) {
            for (int i = 0; i < 10000; i++) {
                if (i % 10000 == 0 && j % 10000 == 0) {
                    System.out.print(msg);
                }
            }
        }

        t1.start();

        t2.start();
    }

    public Thread getC1() {
        return c1;
    }

    public Thread getC2() {
        return c2;
    }
}

class Target1 implements Runnable {

    String msg;

    Target1(String msg) {
        this.msg = msg;
    }

    @Override
    public synchronized void run() {
        for (int j = 0; j < 100000; j++) {
            for (int i = 0; i < 100000; i++) {
                if (i % 100000 == 0 && j % 10000 == 0) {
                    System.out.print(msg);
                }
            }
        }
        try {

            notifyAll();
            System.out.println("K");
        } catch (IllegalMonitorStateException e) {
            System.out.println("\nIllegalMonitorStateException!! in " + msg + "\n");
        }
    }
}

wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). wait()告诉调用线程放弃监视器,然后进入睡眠状态,直到其他线程进入同一监视器并调用notify()。 Unable to get same monitor when calling notify .How to do this? 调用notify时无法获得同一监视器。如何执行此操作? and what does its importance? 它的重要性是什么?

You should avoid wait()/notify() and wherever possible use the higher-level abstractions Java provides, see: Java Concurrency Tutorial . 您应该避免使用wait()/ notify(),并尽可能使用Java提供的更高级别的抽象,请参阅: Java并发教程

Using wait()/notify(), you must use the same monitor for both calls, see Guarded Blocks . 使用wait()/ notify(),两个调用必须使用相同的监视器,请参阅Guarded Blocks Even if this is only for learning, I don't see a good way of making this work with wait(). 即使这只是为了学习,我也没有看到使用wait()进行这项工作的好方法。 You should either stick to join() or use one of the higher-level abstractions. 您应该坚持使用join()或使用更高级别的抽象之一。

As i don't have enough reputation to comment, commenting via answer 由于我没有足够的声誉来发表评论,因此通过答案发表评论

You are not locking and notifying on same object. 您没有锁定并通知同一对象。

you are locking on mainT but notifying on Target1 instance, you need to pass the locking object to c1 and c2 . 您要锁定mainT但要通知Target1实例,则需要将锁定对象传递给c1c2

however i suggest you to use java concurrent API to solve such problems 但是我建议您使用Java并发API解决此类问题

What about : 关于什么 :

public static void main(String[] args) throws InterruptedException {
    Thread mainT = Thread.currentThread();
    Target ra = new Target("a");
    Thread t1 = new Thread(ra);
    t1.start();
    t1.getC1().join();
    t1.getC2().join()

    new Thread(new Target("b")).start();
}

See : https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29 参见: https : //docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29

暂无
暂无

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

相关问题 调用notifyAll()时如何获得相同的监视器? - How to get same monitor when calling notifyAll()? 为什么在 java 中使用 wait()、notify()、notifyAll() 时,使用这部分代码的线程必须是唯一拥有它的监视器的线程? - Why when using wait( ) , notify( ) , notifyAll( ) in java the thread using this part of code must be the only thread that own it's monitor? Java 中的线程 | 等待(),通知()和通知所有() - Threads in Java | wait(), notify() and notifyAll() 为什么不调用wait(),notify()或notifyAll()而没有同步块而不是编译器错误? - Why isn't calling wait(), notify() or notifyAll() without a synchronized block not a compiler error? 使用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? 用wait,notify和notifyAll替换Await,Signal,SignalAll - Replace Await, Signal, SignalAll with wait,notify and notifyAll 为什么等待/通知/通知所有方法在 java 中不同步? - why wait/notify/notifyAll methods are not synchronized in java ? 在synchronized语句中的wait(),notify()和notifyAll() - wait(), notify() and notifyAll() inside synchronized statement 如何使用notify和notifyall解决饥饿问题? - How to solve starvation with notify and notifyall?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM