【问题标题】:Why synchronized can not synchronize thread?为什么synchronized不能同步线程?
【发布时间】:2020-01-26 05:01:29
【问题描述】:

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

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();
    }
}

【问题讨论】:

  • 我想不通。请帮帮我-0-
  • 此代码不会按原样编译。请编辑并确保它可以编译。
  • 如果没有看到所有代码,我们无法解释这是做什么的。
  • 代码太长。他不允许我全部上传
  • 我使用了多个线程。但结果不是交替调用add()和sub()。

标签: java multithreading synchronized


【解决方案1】:

您似乎假设当您的wait() 调用结束时,flag 已更改为您调用wait() 之前想要的。没有这样的保证,特别是因为您涉及两个以上的线程。您应该检查是否需要继续等待。另见Wait until boolean value changes it state

但总的来说,这些构造太低级而无法使用(除非您想了解细节),您应该查看 concurreny utils 包以获得更简单的高级构造(如队列、锁存器、条件) .

【讨论】:

  • 我有一个问题。我假设标志的值现在是假的。我认为关于 'sub()' 的线程必须等待。我明白你的意思是,当我更改“标志”的值时,一个 sub() 正在运行,另一个 sub() 将被唤醒。但是该方法是由关键字“同步”修改的。这会发生吗?
  • 现在,我只想通过交替执行 add() 和 sub() 来实现这种情况。我知道我的代码中有一些错误。但是我不知道错误在哪里。
  • 如果您希望他们交替使用,您必须确保在恢复之前检查该标志。将if (flag == false) { wait();} 替换为while (flag == false) { wait();}
  • 我不知道它们之间的区别。该方法由“同步”修改。因此,它只会有一个线程调用 sub() 一次。为什么?但结果正是我所期望的
  • 当你wait()你放弃锁,另一个线程可以进入同步块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 2014-10-16
  • 2012-06-13
  • 2021-06-07
  • 1970-01-01
相关资源
最近更新 更多