需要帮助返回线程运行方法中的对象 [英] Need help returning object in thread run method

查看:61
本文介绍了需要帮助返回线程运行方法中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展Thread的Java类,它基本上如下所示:

I have a Java class that extends Thread, it basically looks like the following:

public class HttpRequestDispatcher extends Thread {
    private String url;
    private String method; // GET or POST
    private byte[] postData;

    public HttpRequestDispatcher(String url, String method, byte[] postData) {
        this.url = url;
        this.method = method;
        this.postData = postData;
    }

    public HttpRequestDispatcher(String url, String method) {
        this.url = url;
        this.method = method;
    }

    public void run() {
        ...
    }
}

我需要run()方法来返回ByteArrayOutputStreamString.但是,由于它位于Threadrun()方法中,因此无法将方法的返回类型设置为ByteArrayOutputStreamString.

I need the run() method to return a ByteArrayOutputStream or a String. However, because it is in the run() method of the Thread, I cannot set the return type of the method to a ByteArrayOutputStream or a String.

HttpRequestDispatcher类在名为OAuth.java的类内部被调用.

The HttpRequestDispatcher class is called inside of a class called OAuth.java.

如何解决这种情况?

推荐答案

对此问题有几种解决方案:

There are several solutions to this problem:

  • 使用线程外部的数据结构.在线程即将结束时,将对象传递给构造函数,并对其进行更新.

  • Use an data structure external to the Thread. Pass the object in your constructor and update it, when your Thread is about to finish.

使用回调方法.线程完成后,调用回调.

Use a callback method. When your Thread finishes, call the callback.

使用 java.util.concurrent.Future (Java> = 1.5):

Make use of a java.util.concurrent.Future (Java >= 1.5):

Future表示异步计算的结果.提供了一些方法来检查计算是否完成,等待其完成以及检索计算结果.

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

这篇关于需要帮助返回线程运行方法中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆