为什么同步无法正常工作? [英] Why is synchronized not working properly?
问题描述
这是我的代码:
private int count = 0;
public synchronized void increment() {
count++;
}
public void doWork() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
increment();
System.out.println(count+" "+Thread.currentThread().getName());
}}});
Thread t2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
increment();
System.out.println(count+" "+Thread.currentThread().getName());
}}});
t1.start();
t2.start();
}
这是我的输出:
2 Thread-1
2 Thread-0
3 Thread-1
5 Thread-1
6 Thread-1
4 Thread-0
8 Thread-0
9 Thread-0
7 Thread-1
10 Thread-0
我的理解是increment
是synchronized
.因此,它应该首先increment
一个数字,然后释放lock
,然后将lock
赋予线程t1
或t2
.因此,应该一次increment
一个数字,对吧?
My understanding is that increment
is synchronized
. So, it should first increment
one number and then release the lock
and then give the lock
to the thread t1
or t2
. So, it should increment
one number at a time, right?
但是为什么我的代码incrementing
一次是两个或三个数字?我做错什么了吗(我是新手)?
But why is my code incrementing
two or three numbers at a time? Am I doing something wrong (I'm a newbie)?
推荐答案
虽然count++;
实际上是同步的,但System.out.println(count+" "+Thread.currentThread().getName());
不是同步的,但是它可以访问count
变量.
While count++;
indeed is synchronized System.out.println(count+" "+Thread.currentThread().getName());
is not, but it access to count
variable.
即使您同步了访问权限,它也无济于事,因为下一种情况仍然可能:
Even if you synchronize access, it won't help you because next scenario will be still possible:
- 线程1增量
- 线程2增量
- 线程1的打印值
2
- 线程2的打印值
2
- Thread 1 increment
- Thread 2 increment
- Thread 1 print value
2
- Thread 2 print value
2
要解决此问题,您需要在相同的同步部分中进行递增和打印.例如,您可以将System.out.println(count+" "+Thread.currentThread().getName());
放入increment
方法中.
To fix this issue you need to increment and print in same synchronized section. For example you can put System.out.println(count+" "+Thread.currentThread().getName());
into increment
method.
这篇关于为什么同步无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!