Saturday, 15 July 2017

What is the output of the following code?

public class MultiThreading {
private static class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread("myThread");
myThread.run();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
--

The code above produces the output “main” and not “myThread”. As can be seen in line two of the main() method, we invoke by mistake the method run() instead of start(). Hence, no new thread is started, but the method run() gets executed within the main thread.

No comments:

Post a Comment