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大家帮帮忙解释一下
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大家帮帮忙解释一下
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
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无法保证。