java - run完成后调用线程对象方法

标签 java multithreading jvm

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

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

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

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

我需要使用事件机制吗?

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

最佳答案

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

}

关于java - run完成后调用线程对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926588/

相关文章:

java - java中如何判断线程池中是否有可用线程

android - 如何从可移植驱动器运行用于 Android 开发的 JVM、SDK 和 eclipse?

java - 一些SerialCG日志的含义

java - 加载驱动和注册驱动的区别

java - 查找到所选点特定距离内的所有地址的最佳方法是什么

java - 找不到 taskdef ant 任务

java - IntentBuilder(Context,ComponentName) 在 IntentBuilder 中具有私有(private)访问权限

java - 线程状态java

c - 基于线程计算分配共享内存

java - Eclipse java lwjgl java.library.path 中没有 lwjgl