1.What is the importance of "static" in "public static void main(String arg[])" in java? 2.Can we implement runnable and insatntiate Thread class simultaneously? or How is it related to each other?
You can extend Thread and implement Runnable at the same time, but it isn't necessary because the class Thread already implements Runnable. That means that any subclass of Thread that you create will also implement Runnable by default.
static means that a method belongs to the class rather than any instance of the class. That means that you can use the method without creating an instance of the class. It's important in main because main is your entry point into the program - you call main before you've created any instances of the class that your main method is in. Because it's static you can do that. Every thread needs a run() method - this abstract method is in the Runnable interface - but you have to write a method body for it. There's two ways of doing this. You can extend the class Thread which implements Runnable and write your own run() method, doing something like this:- class MyThread extends Thread{ public void run(){ for (int i =0; i<50; i++) { System.out.println("This thread is running"); } } If you then create an instance of MyThread, you have a thread with it's own run method. You can call the start() method of this instance of MyThread (it inherits start() from Thread), and the thread scheduler knows it can call the run() method defined in the MyThread class. The other alternative is that you can use a Runnable object. That's an instance of a class that you define that implements Runnable. This class needs to contain a method body for the abstract method run() in Runnable. For example: class MyRunnable implements Runnable{ public void run() { for (int i=0; i<50; i++) { System.out.println("The Runnable object's run is running"); } } } You then use a special constructor of the Thread class, passing in a Runnable object. The code looks something like this:- MyRunnable runObj = new MyRunnable(); Thread t1 = new Thread(runObj); Now you can call t1.start() and when the scheduler allows the thread some time, the run method defined in MyRunnable is invoked. I guess you could implement Runnable and instantiate a Thread object at the same time using an anonymous class like this:- Thread t1 = new Thread( new Runnable(){ public void run(){ // do the run method stuff here } });
I don't know how often you would do this though. Kathy