user482594
user482594

Reputation: 17486

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

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);



    }


}

Upvotes: 5

Views: 18738

Answers (3)

Nathan Hughes
Nathan Hughes

Reputation: 96385

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.

Upvotes: 12

bigwheels16
bigwheels16

Reputation: 892

Change new Thread(this) to new Thread(new Server()):

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(new Server());



    }


}

Upvotes: 3

fatnjazzy
fatnjazzy

Reputation: 6152

class SimpleThread extends Thread {
    public SimpleThread(String name) {
        super(name);
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " thread: " + getName());
            try {
                sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {}
        }
        System.out.println("DONE! thread: " + getName());
    }
}

class TwoThreadsTest {
    public static void main (String[] args) {
        new SimpleThread("test1").start();
        new SimpleThread("test2").start();
    }
}

Upvotes: 0

Related Questions