完成运行后调用线程对象方法

时间:2014-11-14 09:19:45

标签: java multithreading jvm

我正在编写一个在单独的线程上读取远程文件数据的类。

该类继承自线程并在run方法中读取一些远程文件数据。我将数据存储在字符串中。

我可以添加其他返回此数据字符串的方法吗?

我看到在运行方法返回后isalive返回false值。

我是否需要使用事件机制?

请提出一些更好的解决方法。

2 个答案:

答案 0 :(得分:1)

<强>路#1

改为使用Callable,并从Future获取此字符串。

点击此处查看返回字符串的example

像这样:

public class GetDataCallable implements Callable<String> {  
    @Override
    public String call() throws Exception {
        return getDataFromRemote(); //get from file and returns
    }

}

你使用像

这样的东西
    GetDataCallable <String> task = new GetDataCallable <String>();
    ExecutorService service = Executors.newFixedThreadPool(1);
    Future<String> future =service.submit(task);//run the task in another thread,
    ..//do any thing you need while the thread is runing 
    String data=future.get();//Block and  get the returning string from your Callable task

如果您坚持使用Thread,可以尝试以下两种方式

<强>路#2

public youThread extends Thread{
     private String data;//this is what you need to return

     @Override
     public void run(){
         this.data=//get from remote file.
     }

     public String getData(){
          return data;
     }
}

但是你必须在调用getData()之前确保线程完成,例如,你可以使用thread.join()来做到这一点。

thread.start()
..//some jobs else
thread.join();
String data=thread.getData();

<强>路#3

run()

的末尾使用一些静态回调方法

  public Class StoreDataCallback{
    public static void storeData(String data_from_thread){
          objectCan.setData(data_from_thread);//get access to your data variable and assign the value 
    }
}

public Class YourThread extends Thread{

     @Override
     public void run(){
       String data =getDataFromRemote();//do some thing and get the data.
       StoreDataCallback.storeData(data);
    }

}

答案 1 :(得分:0)

我会在你的情况下使用Callable,例如

Callable<String> callable = new Callable<String>() {

    @Override
    public String call() throws Exception {
        // do your work here and return the result
        return "Hello";
    }
};

直接(在同一个线程中)或使用ExecutorService

执行callable
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> result = executorService.submit(callable);
System.out.println(result.get());

或仅使用FutureTask执行Callable

FutureTask<String> task = new FutureTask<String>(callable);
Thread taskRunner = new Thread(task); 
taskRunner.start();

String result = task.get();