为什么同步无法同步线程?

问题描述 投票:0回答:1

我已经设置了标志的值,但是结果不是'add'和'sub'交替出现。为什么?当我查看结果时,它执行了两次“ sub”方法。但是,当“ sub”方法结束时,标志的值将设置为“ false”。但是结果,它连续两次打印了“ subxxxxx”。

class Resource {
    private boolean flag = true;
    private int num = 0;

// At here I have declared an add()
    public synchronized void add() throws InterruptedException {
        if (this.flag == false) {
            super.wait();
        }
        Thread.sleep(100);
        this.num++;
        System.out.println("addition:"+Thread.currentThread().getName() + this.num);
        this.flag = false;
        super.notifyAll();
    }

// At here I have declared an sub()
    public synchronized void sub() throws InterruptedException {
        if (this.flag == true) {
            super.wait();
        }
        Thread.sleep(200);
        this.num--;
        System.out.println("subtraction:"+Thread.currentThread().getName() + this.num);
        this.flag = true;
        super.notifyAll();
    }
}

/*
* I will test it with multiple threads. For example:
*new Thread(ad, "add").start();
*new Thread(ad, "add").start();
*new Thread(sub, "sub").start();
*new Thread(sub, "sub").start();
*When threads start. it will execute alternately. For example:
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
But the result is like this:
Thread add:0
Thread sub:-1
Thread sub:-2
Thread add:-1
Thread sub:-3
Thread sub:-4
Why?Why?Why?
*/
        new Thread(ad, "add").start();
        new Thread(ad, "add").start();
        new Thread(sub, "sub").start();
        new Thread(sub, "sub").start();
    }
}
java multithreading synchronized
1个回答
0
投票

您似乎假设wait()通话结束时,flag已更改为您想在调用wait()之前要拥有的内容。没有这样的保证,尤其是因为您涉及两个以上的线程。您应该检查是否需要继续等待。另请参阅Wait until boolean value changes it state

但是总的来说,这些结构太低了,无法使用(除非您想学习基本知识),并且您应该查看并发utils包,以获得更简单的高层结构(例如Queues,Latches,Conditions)。

© www.soinside.com 2019 - 2024. All rights reserved.