提问一道scjp的题。

「已注销」 2009-10-31 08:14:56
Question 90
Given:
1. public class MyLogger {
2. private StringBuilder logger = new StringBuuilder();
3. public void log(String message, String user) {
4. logger.append(message);
5. logger.append(user);
6. }
7. }
The programmer must guarantee that a single MyLogger object works
properly for a multi-threaded system. How must this code be changed
to be thread-safe?
A. synchronize the log method
B. replace StringBuilder with StringBuffer
C. No change is necessary, the current MyLogger code is already
thread-safe.
D. replace StringBuilder with just a String object and use the string
concatenation (+=) within the log method
Answer: A大家帮帮忙解释一下
...全文
105 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Sodino 2009-10-31
  • 打赏
  • 举报
回复
虽然StringBuffer是thread-safe的,但是用于本题却不代表执行结果是thread-safe.

从本题的意思来看,原子操作为:
4. logger.append(message);
5. logger.append(user);
4,5步依次一次性执行或要嘛都不执行。

在multi-thread,如果多个线程都申请调用public void log(String message, String user)方法,在该方法没有加synchronized标识符的情况下,可能会出现message和user不是成对依次加入的情况。可能会出现
mes mes user user这样的的错误的结构。

所以选择A,对logger的操作是线程安全的。选B无法保证。
zxj828282 2009-10-31
  • 打赏
  • 举报
回复
那B为什么不行呢
「已注销」 2009-10-31
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 blliy117 的回复:]
A. synchronize the log method
B. replace StringBuilder with StringBuffer
C. No change is necessary, the current MyLogger code is already
thread-safe.
D. replace StringBuilder with just a String object and use the string
concatenation (+=) within the log method
Answer: A大家帮帮忙解释一下

A. synchronize the log method 意思就是public void log(String message, String user)
--》public synchronize  void log(String message, String user)
我感觉也是A
[/Quote]那B为什么不行呢
苍蝇①号 2009-10-31
  • 打赏
  • 举报
回复
因为加了synchronize后,就等于在对象上加了锁,锁的粒度是整个对象。所以在多线程环境中只可能一个线程获得此对象锁,也就说只能一个接一个的线程来访问此对象,因此答案为A 别的三个都非线程安全
blliy117 2009-10-31
  • 打赏
  • 举报
回复
A. synchronize the log method
B. replace StringBuilder with StringBuffer
C. No change is necessary, the current MyLogger code is already
thread-safe.
D. replace StringBuilder with just a String object and use the string
concatenation (+=) within the log method
Answer: A大家帮帮忙解释一下

A. synchronize the log method 意思就是public void log(String message, String user)
--》public synchronize void log(String message, String user)
我感觉也是A
wxzyydy 2009-10-31
  • 打赏
  • 举报
回复
帮楼主顶顶,答案是选A

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧