Which three will compile and run without exception? (Choose three.)
A. private synchronized Object o;
B. void go(){
synchronized(){/* code here */}
C. public synchronized void go(){/* code here */}
D. private synchronized(this) void go(){/* code here */}
E. void go(){
synchronized(Object.class){/* code here */}
F. void go(){
Object o = new Object();
synchronized(o){/* code here */}
答案:CEF 我觉得答案错了,F无法保证加锁,因为锁对象是临时变量o,那么每个线程进入go的时候都可以可以获得一个不同的o,从而可以加上锁,我下面的代码也验证了这点,还有对于D,是否正确呢?public class Threads4 {
Object obj = new Object();
public static void main(String[] args) throws Exception {
class Mythread implements Runnable {
Threads4 t4; Mythread(Threads4 t4) {
this.t4 = t4;
} public void run() {
// System.out.println("start " + Thread.currentThread().getId());
try {
t4.go();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("end " + Thread.currentThread().getId());
}
}
Threads4 t4 = new Threads4(); Thread t1 = new Thread(new Mythread(t4));
Thread t2 = new Thread(new Mythread(t4));
t1.start();
// Thread.sleep(2000);
t2.start();
} public void go() {
synchronized (obj) {
double d;
System.out.println(Thread.currentThread().getId()+" in loop");
for (int i = 0; i < 100; i++)
// for (int j = 0; j < 1000000; j++)
// for (int k = 0; k < 1000000; k++)
System.out.println(Thread.currentThread()); System.out.println(Thread.currentThread().getId()+" out of loop");
}
}}
A. private synchronized Object o;
B. void go(){
synchronized(){/* code here */}
C. public synchronized void go(){/* code here */}
D. private synchronized(this) void go(){/* code here */}
E. void go(){
synchronized(Object.class){/* code here */}
F. void go(){
Object o = new Object();
synchronized(o){/* code here */}
答案:CEF 我觉得答案错了,F无法保证加锁,因为锁对象是临时变量o,那么每个线程进入go的时候都可以可以获得一个不同的o,从而可以加上锁,我下面的代码也验证了这点,还有对于D,是否正确呢?public class Threads4 {
Object obj = new Object();
public static void main(String[] args) throws Exception {
class Mythread implements Runnable {
Threads4 t4; Mythread(Threads4 t4) {
this.t4 = t4;
} public void run() {
// System.out.println("start " + Thread.currentThread().getId());
try {
t4.go();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("end " + Thread.currentThread().getId());
}
}
Threads4 t4 = new Threads4(); Thread t1 = new Thread(new Mythread(t4));
Thread t2 = new Thread(new Mythread(t4));
t1.start();
// Thread.sleep(2000);
t2.start();
} public void go() {
synchronized (obj) {
double d;
System.out.println(Thread.currentThread().getId()+" in loop");
for (int i = 0; i < 100; i++)
// for (int j = 0; j < 1000000; j++)
// for (int k = 0; k < 1000000; k++)
System.out.println(Thread.currentThread()); System.out.println(Thread.currentThread().getId()+" out of loop");
}
}}
LZ好像没看清楚题目问的是啥 compile and run without exception说的是代码上的不是功能上的只要能通过编译并运行就得选
F.编译运行没问题,所以得选