Java:定期从线程向主类发送数据

时间:2014-09-02 02:37:38

标签: java multithreading

我有从HTTP下载数据的线程。我使用流API每1秒到大约10分钟得到它。

从HTTP服务器接收数据后,我需要将此数据发送到MyMainClass中的方法。如果没有静态方法,我怎么能这样做?我不想使用静态方法。

public class MyMainClass {  
    public static void main(String[] args) {            
        GetData getData = new GetData();
        getData.start();        
    }

    public static void useText(String text) {
        System.out.println(text);
        // do something...          
    }
}


public class GetData extends Thread {

    @Override
    public void run() {
        String text;

        /* Download text from HTTP and save it to "text".
         * Every 1 seconds to about 10 minutes using stream API.
         * text= "abc...";
         * If there are no errors, run method never exit.
         */
        MyMainClass.useText(text);

    }
}

1 个答案:

答案 0 :(得分:2)

使您的方法成为实例方法并创建可传递给Thread实例的类的实例

public static void main(String[] args) {            
    GetData getData = new GetData(new MyMainClass());
    getData.start();        
}

public void useText(String text) {
    System.out.println(text);
    // do something...          
}

GetData类'run方法中,您可以使用MyMainClass实例作为回调。

public GetData extends Thread {
    public GetData(MyMainClass instance) {
        this.instance = instance;
    }

    private MyMainClass instance;

    @Override
    public void run() {
        String text;

        /* Download text from HTTP and save it to "text".
         * Every 1 seconds to about 10 minutes using stream API.
         * text= "abc...";
         * If there are no errors, run method never exit.
         */
        instance.useText(text);
    }
}