Java 在执行相同操作的线程上使用等待/通知方法



我试图理解 Java 上的监视器,我遇到的问题是如何使运行相同同步方法的线程等待?我试图制作一个简单的程序,使 3 个线程使用相同的方法添加到 N 元素 1 总共 10 000 次,我想知道如何让其他线程在执行添加方法时等待并通知所有完成后,如果我同时启动所有这些线程。

这是我编写的没有等待/通知函数的程序:

class Swapper implements Runnable{
    int number;
    Swapper(int number){
        this.number=number;
    }
    @Override
    public void run() {
        while (mainClass.counter>0){
            mainClass.incArrayElement(number);
        }
    }
}
public class mainClass {
    public static volatile int counter = 10000;
    public static volatile int[] testArray = new int[]{0,0,0};
    public static synchronized void incArrayElement(int index){
        if (counter>0) {
            testArray[index - 1]++;
            counter--;
        }
        else {
            return;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Swapper(1));
        Thread thread2 = new Thread(new Swapper(2));
        Thread thread3 = new Thread(new Swapper(3));
        thread1.start();
        thread2.start();
        thread3.start();
        thread1.join();
        thread2.join();
        thread3.join();
        int checkSum = 0;
        for (int i = 0; i < testArray.length; i++) {
            System.out.println(testArray[i]);
            checkSum+=testArray[i];
        }
        System.out.println(checkSum);
    }
}

当线程调用类的同步方法"incArrayElement"时,它会获取该对象的锁,只要获取锁的先前线程不释放锁,任何新线程都不能调用同一对象的任何同步方法。因此,所有其他线程将被阻塞,直到执行完成。

那么为什么你需要让线程调用wait((,因为它们已经被阻止并等待。

不幸的是,

您的示例没有很好地选择。

声明synchronized的方法以其他线程无法调用它的方式进行控制,除非它已完成执行。然后其中一个线程再次调用此方法。"哪个线程"无法真正分辨,因为您无法控制它。使用 waitnotify 函数不会让您控制这一点。因此,如果这就是你要寻找的,你就无法实现你想要的。它对你来说仍然是不确定的。

如果只是确保一次仅由一个线程调用该方法,那么您已经具有该行为,无需waitnotify

最新更新