开发者

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

I believe variables us开发者_开发技巧ed 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);



    }


}


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.


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



    }


}


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜