从Java中的Runnable(Thread)获取返回值

时间:2015-05-17 17:02:01

标签: java android multithreading runnable

这个线程完成后,有没有办法让我传递“r”的值?我相信我在9或10个月前在另一个项目上做过这件事,但对于我而言,我不记得找到代码的项目了。我花了大约5个小时来挖掘代码和谷歌搜索,但是由于我不经常在Java \ Android中开发,所以我已经完全放弃了我的想法。

以下是我的代码,以及我上次做这个时的记忆。我有点记得“.call()”或“.get()”,但试图在android文档中找到一些东西。我不确定。我只能找到“可赎回”。

public void updateUserProfile(){

if(checkFields(){
//Do Something
}else{
//Do Something
}

}


 public boolean checkFields(){

Boolean r = false;



     Runnable run = new Runnable(){
                    //Boolean r;
                @Override
                public void run() {

                    //Or boolean r;

                    //get value of r.
                    r = php.UpdateProfile.updateProfile(user_id, user_email);
                }
            };

            new Thread(run).start();

            return r; //run.get(r)?
}

5 个答案:

答案 0 :(得分:5)

您正在做的是创建一个实现Runnable的匿名内部类的实例。因此,您可以访问包含类的字段。将代码的结果存储在其中一个中。

当然要小心在主线程和你在这里创建的线程之间同步对这个结果变量的访问。

public class TestThreads {
    static int r = 0;
    public static void main(String[] args) {
        Runnable run = new Runnable() {
            public void run() {
                r = 20;
            }
        };
        Thread t = new Thread(run);
        t.start();
        try {
            t.join();
        }
        catch(InterruptedException e) {
            return;
        }
        System.out.println("Result: " + r);
    }
}

答案 1 :(得分:0)

您不能从返回类型为Void的方法返回值。

使用Handler类发送消息,并从线程的运行方法中调用handler.sendMessage()并在onHandleMessage Handler上处理此消息

Handler Document link

Handler example

答案 2 :(得分:0)

尝试使用FutureCallableExecuterService ...这可能会有所帮助http://www.journaldev.com/1090/java-callable-future-example

答案 3 :(得分:0)

Runnable不会返回。您将需要使用实现Callable的Future或使用FutureTask。

ExecutorService pool = Executors.newFixedThreadPool(poolSize);
FutureTask<String> future =
   new FutureTask(new Callable() {
   public String call() {
      String res = ...;
      return res;
});
pool.execute(future);

String res = future.get(); 
// use the line below if you want to set a timeout for the task
String res = future.get(timeoutmillis, TimeUnit.MILLISECONDS);

答案 4 :(得分:0)

我最终使用了AsyncTask。希望保持它超级简单,因为支持要求,但AsyncTask做了我需要它。

private class updateUserProfile extends AsyncTask<Boolean, Boolean, Boolean>{


        @Override
        protected Boolean doInBackground(Boolean... params) {

            return php.UpdateProfile.updateProfile(etEditAddress.getText().toString(),
                    etEditCity.getText().toString(),
                    spnStates.getSelectedItem().toString(), etEditZip.getText().toString(), etEditPhone.getText().toString(), etEditAddress.getText().toString());;
        }

        public void onPostExecute(String result) {
            // execution of result of Long time consuming operation
            Toast.makeText(MyAccount.this, result.toString(), Toast.LENGTH_LONG).show();
        }

    }
相关问题