簡體   English   中英

如何在Java應用程序中從Main方法運行線程?

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

我相信static main方法中使用的變量也應該是static 問題是我根本不能在這個方法中使用this 如果我沒記錯的話,我必須使用commnad myThread = new ThreaD(this)啟動線程。

以下代碼產生錯誤,因為我在線程啟動中使用了this 我在這做錯了什么?

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



    }


}

你不能使用this因為main是一個靜態方法, this是指當前實例而沒有。 您可以創建一個可以傳遞給線程的Runnable對象:

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

這將導致您在Server類的run方法中放置的任何內容都由myThread執行。

這里有兩個獨立的概念,Thread和Runnable。 Runnable指定需要完成的工作,Thread是執行Runnable的機制。 雖然Thread有一個可以擴展的run方法,但是你可以忽略它並使用一個單獨的Runnable。

new Thread(this)更改為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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM