Welcome Guest | Sign in | Register
Threads - Discussion Page For Q.2952 | Java Programming Questions and Answers | Java Programming Free Online-Tests | LucentBlackBoard | LucentBlackBoard.com

Home > Java Programming > Threads > Questions and Answers

Q: What is the output for the below code ?

public class B {
public synchronized void printName(){
try{
System.out.println("printName");
Thread.sleep(5*1000);
}catch(InterruptedException e){
}
}
public synchronized void printValue(){
System.out.println("printValue");
}
}
public class Test extends Thread{
B b = new B();
public static void main(String argv[]) throws Exception{
Test t = new Test();
Thread t1 = new Thread(t,"t1");
Thread t2 = new Thread(t,"t2");
t1.start();
t2.start();
}
public void run(){
if(Thread.currentThread().getName().equals("t1")){
b.printName();
}else{
b.printValue();
}
}
}
A. print : printName , then wait for 5 seconds then print : printValue B. print : printName then print : printValue
C. print : printName then wait for 5 minutes then print : printValue D. Compilation succeed but Runtime Exception

Answer and Explanation

Answer:print : printName , then wait for 5 seconds then print : printValue

Explanation:
There is only one lock per object, if one thread has picked up the lock, no other thread can pick up the lock until the first thread releases the lock. printName() method acquire the lock for 5 seconds, So other threads cannot access the object. If one synchronized method of an instance is executing then other synchronized method of the same instance
should wait.

Comment on this Question

Name:

Loading...




Partner Sites
LucentBlackBoard.com                  SoftLucent.com                  LucentJobs.com
All rights reserved © 2012-2015 SoftLucent.