Monday, May 24, 2010

Which statement is true about the output result of the following program?

public class PingPong {





public static synchronized void main(String[] a) {


Thread t = new Thread() {





@Override


public void run() {


pong();


}


};





t.run();


System.out.print("Ping");


}





static synchronized void pong() {


System.out.print("Pong");


}


}





a. PingPong always


b. PingPong sometimes and PongPing sometimes


c. PongPing always since it's not a multi-threaded program


d. There will be an Exception

Which statement is true about the output result of the following program?
why dont you learn java and answer it yourself
Reply:The answer is (b).





When you call t.run(), you start a new thread of execution, hence, you would have two threads in all (the new one %26amp; the main thread). A thread's behavior in most cases is unpredictable as would be here. If pong() is invoked first, Pong would be printed first, else Ping would be printed. Again, anything can happen at runtime!


No comments:

Post a Comment