后面的代码给出了我无法理解的输出。
我有2个整数:计数和锁定。如果我同步“锁定”(如代码中所示),则输出显示“count”按预期添加,但“锁定”添加错误。
为什么会这样?
如果我同步它,我无法改变“锁定”吗?
以下是代码:
public class SynchronizedTest implements Runnable {
static Integer count = new Integer(0);
static Integer lock = new Integer(0);
private int threadIndex = -1;
public SynchronizedTest(int threadIndex) {
this.threadIndex = threadIndex;
}
@Override
public void run() {
System.out.println("in");
for (int i = 0; i < 10; ++i) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (SynchronizedTest.lock) {
count++;
lock++;
System.out.println("Thread " + threadIndex + ": " + count);
System.out.println("Thread " + threadIndex + " lock : " + lock);
}
}
System.out.println("out");
}
public static void main(String[] args) {
for (int i = 0; i < 5; ++i) {
SynchronizedTest threadTest = new SynchronizedTest(i);
Thread thread = new Thread(threadTest);
thread.start();
}
}
}
输出结果为:
in
in
in
in
in
Thread 4: 1
Thread 4 lock : 1
Thread 0: 2
Thread 0 lock : 2
Thread 1: 3
Thread 3: 4
Thread 1 lock : 4
Thread 3 lock : 4
Thread 2: 5
Thread 2 lock : 5
Thread 1: 6
Thread 1 lock : 6
Thread 3: 7
Thread 3 lock : 7
Thread 4: 8
Thread 2: 10
Thread 0: 9
Thread 2 lock : 10
Thread 4 lock : 10
Thread 0 lock : 10
Thread 1: 11
Thread 0: 14
Thread 0 lock : 14
Thread 2: 13
Thread 2 lock : 14
Thread 3: 12
Thread 3 lock : 14
Thread 1 lock : 14
Thread 4: 15
Thread 4 lock : 15
Thread 0: 16
Thread 0 lock : 16
Thread 2: 17
Thread 1: 19
Thread 1 lock : 19
Thread 3: 18
Thread 3 lock : 19
Thread 2 lock : 19
Thread 4: 20
Thread 4 lock : 20
Thread 1: 21
Thread 1 lock : 21
Thread 2: 22
Thread 0: 23
Thread 2 lock : 23
Thread 0 lock : 23
Thread 3: 24
Thread 3 lock : 24
Thread 4: 25
Thread 4 lock : 25
Thread 1: 26
Thread 1 lock : 26
Thread 2: 27
Thread 3: 29
Thread 0: 28
Thread 3 lock : 29
Thread 2 lock : 29
Thread 0 lock : 29
Thread 4: 30
Thread 4 lock : 30
Thread 1: 31
Thread 1 lock : 31
Thread 3: 32
Thread 0: 33
Thread 3 lock : 33
Thread 0 lock : 33
Thread 2: 34
Thread 2 lock : 34
Thread 4: 35
Thread 4 lock : 35
Thread 1: 36
Thread 1 lock : 36
Thread 3: 37
Thread 3 lock : 37
Thread 2: 39
Thread 0: 39
Thread 2 lock : 39
Thread 0 lock : 39
Thread 4: 40
Thread 4 lock : 40
Thread 1: 41
Thread 1 lock : 41
Thread 3: 42
Thread 0: 43
Thread 3 lock : 43
Thread 0 lock : 43
Thread 2: 44
Thread 2 lock : 44
Thread 4: 45
Thread 4 lock : 45
Thread 1: 47
Thread 2: 49
Thread 2 lock : 49
Thread 0: 48
Thread 3: 47
Thread 3 lock : 49
out
Thread 0 lock : 49
out
out
Thread 1 lock : 49
out
Thread 4: 50
Thread 4 lock : 50
out
答案 0 :(得分:0)
您没有使用相同的锁,因为您正在更改整数,每次增加锁时都会创建一个新对象,只需使用一个新对象而不要更改。