How can I run thread from Main method in Java application?

user482594 picture user482594 · Jul 29, 2011 · Viewed 16.7k times · Source

I believe variables used in static main method should be also static as well. The problem is that I cannot use this in this method at all. If I remember correctly, I have to initiate thread with commnad myThread = new ThreaD(this).

The below codes produces an error because I used this in thread initiation. What have I done wrong here?

package app;

public class Server implements Runnable{

    static Thread myThread;


    public void run() {
        // TODO Auto-generated method stub  
    }

    public static void main(String[] args) {
        System.out.println("Good morning");

        myThread = new Thread(this);



    }


}

Answer

Nathan Hughes picture Nathan Hughes · Jul 29, 2011

You can't use this because main is a static method, this refers to the current instance and there is none. You can create a Runnable object that you can pass into the thread:

myThread = new Thread(new Server());
myThread.start();

That will cause whatever you put in the Server class' run method to be executed by myThread.

There are two separate concepts here, the Thread and the Runnable. The Runnable specifies what work needs to be done, the Thread is the mechanism that executes the Runnable. Although Thread has a run method that you can extend, you can ignore that and use a separate Runnable.