有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    以下是在Java中与ThreadExecutor一起使用wait notify的示例:

    public class ExecutorServiceTest {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(2);
            ThreadB threadB = new ThreadB();
            ThreadA threadA = new ThreadA(threadB);
    
            executor.execute(threadA);
            executor.execute(threadB);
    
            executor.shutdown();
            while (!executor.isTerminated());
            System.out.println("Finished all threads");
    
        }
    
        static class ThreadA extends Thread {
    
            private final ThreadB waitThread;
    
            public ThreadA(ThreadB waitThread) {
                this.waitThread = waitThread;
            }
    
            @Override
            public void run() {
                synchronized (waitThread) {
                    try {
                        waitThread.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                    System.out.println("B Count Total : " + waitThread.getCount());
    
                    for (int i = waitThread.getCount(); i < 200; i++) {
                        System.out.println("A Counting " + i);
                    }
                }
            }
        }
    
        static class ThreadB extends Thread {
    
            private int count = 0;
    
            @Override
            public void run() {
                synchronized (this) {
                    while (count < 100) {
                        System.out.println("B Counting " + count);
                        count++;
                    }
                    notify();
                }
            }
    
            public int getCount() {
                return count;
            }
    
        }
    
    }
    

    同步的

    keyword is used for exclusive accessing.

    To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.

    synchronized statements must specify the object that provides the intrinsic lock:

    等等

    tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

    通知

    wakes up the first thread that called wait() on the same object.