【问题标题】:Calling thread object method after completion of run运行完成后调用线程对象方法
【发布时间】:2015-01-11 15:26:47
【问题描述】:

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

这个类继承自线程,在run方法中读取一些远程文件数据。我把数据存储在一个字符串中。

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

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

我需要使用事件机制吗?

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

【问题讨论】:

  • Thread 继承是一种不好的做法。将您的代码放入Runnable

标签: java multithreading jvm


【解决方案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种方式

方式#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);
    }

}

【讨论】:

  • Jaskey,谢谢。在run方法完成的时候,线程对象的isalive是假的。即使isalive是假的,我可以调用getData方法吗?
  • @ramu,我没试过,看这里stackoverflow.com/questions/17293304/…
【解决方案2】:

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

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

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

直接(在同一个线程中)执行可调用对象或使用 ExecutorService

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 2019-09-26
    • 2021-10-02
    相关资源
    最近更新 更多