SCJP真题库更新五
QUESTION 14
Given the exhibit:
Which statement is true?
A. This code may throw an InterruptedException
B. This code may throw an IllegalStateExcepion
C. This code may throw a TimeOutException after ten minutes
D. This code will not compile unless "obj.wait ( ) \" is replaced with " (( Thread) obj) .wait ( )"
E. Reversing the order of obj.wait ( ) and obj. notify ( ) may vcause this method to complete normally
Answer: ( A )
首先编译通不过,
第5行:void waitForSignal() throws InterruptedException{…….}
第6行: Object obj=new Object();
obj=Thread.currentThread();
第7行应该是:synchronized(obj);
-----在写wait()和notify()方法时,除了要写在synchronized区段,.还需要撰写InterruptedException异常的try-catch. 本题就算写了try-catch,也可能会在执行的时候产生current thread not owner的IllegalMonitorStateException 的异常.
参考大纲:多线程 — 同步处理
QUESTION 15
Given the exhibit:
What can be a result?
A. Compilation fails
B. An exception is thrown at runtime
C. The code executes and prints "StartedComplete"
D. The code executes and prints "StartedComplete0123"
E. The code executes and prints "Started0123Complete"
Answer: ( E )
Join()方法使得某个线程加入到正在执行的线程(本题是main线程)中,执行完该线程才继续执行main线程.本程序中第5行由main线程执行,6行因为下达了join(),所以mian的执行将被暂停,等t做完run()方法的全部工作之后,才论到main继续执行未完成的工作!
参考大纲:多线程
QUESTION 16
Which two code fragments will execute the method doStuff ( ) in a separate thread?
(choose two)
A. new Thread ( ) {
public void run ( ) { doStuff ( ); }
};
B. new Thread ( ) {
public void start ( ) { doStuff ( ); }
};
C. new Thread ( ) {
public void run ( ) { doStuff ( ); }
}.run ( );
D. new Thread ( ) {
public void run ( ) { doStuff ( ); }
}.start ( );
E. new Thread (new Runable ( ) {
public void run ( ) { doStuff ( ); }
}. run ( ) ;
F. new Thread (new Runnable ( ) {
public void run ( ) { doStuff ( ); }
}).start ( );
Answer: ( D、F )
D 匿名内部类别中覆写run方法后创建此匿名内部类对象并调用start()方法启动线程。
F 利用匿名内部类来实现runnable接口中的run方法,并调用start()启动线程。
参考大纲:多线程
QUESTION 17
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 ( ) {
synchronized (o) { /* code here */ }
}
Answer: ( C, E, F )
A 错误synchronized不可以成为属性/变量的修饰符
B 错误synchronized ( )中的括号中要加入欲锁定的物件或类型 // synchronized(this)
C 正确 利用synchronized来修饰对象instance方法,锁定的物件将会是this,
D 错误 修饰方法时,this不用特别在synchronized ()中指明
E 正确 合法的 class literals synchronized //针对某个类同步
F 正确 合法的 instance block synchronized //针对某个对象同步
参考大纲:多线程 — 线程同步