需要帮助在线程运行方法中返回对象

编程入门 行业动态 更新时间:2024-10-28 04:21:10
本文介绍了需要帮助在线程运行方法中返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个扩展 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() 方法来返回一个 ByteArrayOutputStream 或一个 String.但是,因为它在Thread的run()方法中,所以我无法将方法的返回类型设置为ByteArrayOutputStream或字符串.

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.

我该如何解决这种情况?

How can I get around this situation?

推荐答案

这个问题有几种解决方案:

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.

更多推荐

需要帮助在线程运行方法中返回对象

本文发布于:2023-11-14 05:03:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586295.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   对象   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!