[英]Why synchronized can not synchronize thread?
I have set the value of the flag, but the result is not 'add' and 'sub' alternates.我已经设置了标志的值,但结果不是 'add' 和 'sub' 交替。 Why?为什么? When I look at the result, it has executed twice the 'sub' method.当我查看结果时,它执行了两次“sub”方法。 But when the 'sub' method ended, the value of the flag will be set 'false'.但是当“sub”方法结束时,标志的值将被设置为“false”。 But as a result, it printed "subxxxxx" twice continuously.但结果,它连续打印了两次“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();
}
}
You seem to assume that when your wait()
call finishes, that the flag
has changed to what you wanted to have before you called wait()
.您似乎假设当您的wait()
调用完成时, flag
已更改为您在调用wait()
之前想要的flag
。 There is no such guarantee, especially since you have more than two threads involved.没有这样的保证,特别是因为您涉及两个以上的线程。 You should check if you need to continue waiting.您应该检查是否需要继续等待。 Also see Wait until boolean value changes it state另请参阅等待布尔值更改其状态
But in general, these constructs are too low-level to use (unless you want to learn the nitty-gritty) and you should look at the concurreny utils package for easier higher-level constructs (like Queues, Latches, Conditions).但总的来说,这些构造太低级而无法使用(除非你想学习细节),你应该查看 concurreny utils 包以获得更简单的高级构造(如队列、锁存器、条件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.