How to use wait and notify in Java without IllegalMonitorStateException?

后端 未结 12 2086
后悔当初
后悔当初 2020-11-22 02:21

I have 2 matrices and I need to multiply them and then print the results of each cell. As soon as one cell is ready I need to print it, but for example I need to print the [

12条回答
  •  抹茶落季
    2020-11-22 03:21

    Simple use if you want How to execute threads alternatively :-

    public class MyThread {
        public static void main(String[] args) {
            final Object lock = new Object();
            new Thread(() -> {
                try {
                    synchronized (lock) {
                        for (int i = 0; i <= 5; i++) {
                            System.out.println(Thread.currentThread().getName() + ":" + "A");
                            lock.notify();
                            lock.wait();
                        }
                    }
                } catch (Exception e) {}
            }, "T1").start();
    
            new Thread(() -> {
                try {
                    synchronized (lock) {
                        for (int i = 0; i <= 5; i++) {
                            System.out.println(Thread.currentThread().getName() + ":" + "B");
                            lock.notify();
                            lock.wait();
                        }
                    }
                } catch (Exception e) {}
            }, "T2").start();
        }
    }
    

    response :-

    T1:A
    T2:B
    T1:A
    T2:B
    T1:A
    T2:B
    T1:A
    T2:B
    T1:A
    T2:B
    T1:A
    T2:B
    

提交回复
热议问题