qq1212 的问题
http://bbs.csdn.net/topics/390383992
如下这段代码,我希望打印0-100,但实际运行还是会产生重复的数,我应该怎么改写代码呢,我已经使用了synchronized关键词啊?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public
class
Test{
public
static
void
main(String[ ] args) {
ThreadTest a =
new
ThreadTest();
for
(
int
i=
0
;i<
100
;i++){
new
Thread(a).start();
a.print();
}
}
}
class
ThreadTest
implements
Runnable {
Count c =
new
Count();
@Override
public
void
run() {
c.increase();
}
public
void
print() {
System.out.println(c.getValue());
}
}
final
class
Count {
private
long
value =
0
;
public
synchronized
long
getValue() {
return
value;
}
public
synchronized
long
increase() {
if
(value == Long.MAX_VALUE) {
throw
new
IllegalStateException(
"error"
);
}
return
++value;
}
}
|
我的答复:
关键是要把两个动作increase和print同步在一起。你代码中的同步synchronized 都是没有意义的。
你比较一下下面两个不同方案的执行结果吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
// 方案1 :同步
public
void
run() {
synchronized
(c) {
// 这里是关键,把(动作1,动作2)同步
// 这意味着,在动作1和动作2之间,别的线程插不进来
c.increase();
// 动作1
try
{
Thread.currentThread().sleep(
100
);
// Sleep 加强观察效果
}
catch
(InterruptedException e) {}
System.out.println(c.getValue());
// 动作2
}
}
// 方案2:无同步
public
void
run() {
c.increase();
// 动作1
try
{
Thread.currentThread().sleep(
100
);
// Sleep 加强观察效果
}
catch
(InterruptedException e) {}
System.out.println(c.getValue());
// 动作2
}
|
另外,
1
2
3
4
5
6
7
8
9
10
11
|
// 方案1 :同步
public
void
run() {
synchronized
(c) {
//...body
}
}
// 等同于:
public
synchronized
void
run() {
//...body
}
|
连接