Welcome Guest | Sign in | Register
Threads - Discussion Page For Q.2953 | 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 static 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 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. In this case printName() is static , So lock is in class B not instance b, both method (one static and other no-static) can run simultaneously. A static synchronized method and a non static synchronized method will not block each other.

Comment on this Question

Name:

Loading...




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