我下面有一个线程类,它从一个 url 读取一个文件,然后将结果存储在一个公共(public)静态变量中,以便可以从其他类访问它。有没有更好的方法来实现这一目标?
谢谢
public class ReadContent implements Runnable{
private HttpConnection connection;
private InputStream inputStream;
private String url;
public ReadContent(String url){
this.url = url;
}
public void run() {
readContentURL();
}
private void readContentURL() {
try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("Connection", "close");
inputStream = connection.openDataInputStream();
// inputStream = getClass().getResourceAsStream(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c ;
while (true) {
c = inputStream.read();
if (c == -1)
break;
baos.write(c);
}
SavedJSON.result = new JSONObject(new String(baos.toByteArray()));
}
catch(Exception e){
e.printStackTrace();
}
}
}
这是我提出的解决方案 -
public class MyFuture{
private final Object lock = new Object();
private JSONObject value;
public void set(JSONObject t){
value = t;
synchronized(lock){
value = t;
lock.notifyAll();
}
}
public JSONObject get(){
synchronized(lock){
while(value == null)
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}
}
public class SavedJSON {
public static MyFuture result;
}
public class ReadContent implements Runnable{
private HttpConnection connection;
private InputStream inputStream;
private String url;
public ReadContent(String url){
this.url = url;
}
public void run() {
readContentURL();
}
private void readContentURL() {
try {
int len = 0;
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
// connection.setRequestProperty("Connection", "close");
inputStream = connection.openDataInputStream();
// inputStream = getClass().getResourceAsStream(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c ;
while (true) {
c = inputStream.read();
if (c == -1)
break;
++len;
baos.write(c);
}
SavedJSON.result.set(new JSONObject(new String(baos.toByteArray(), 0, len, "utf-8")));
}
catch(Exception e){
e.printStackTrace();
}
}
}
最佳答案
由于您不能使用 Callable(而且我假设您也不能使用 Future),您可以尝试创建自己的 Future。它相对简单:
public class MyFuture<T>{ // can you not use generics either?
private final Object lock = new Object();
private T value;
public void set(T t){
synchronized(lock){
value = t;
lock.notifyAll();
}
}
public T get(){
synchronized(lock){
while(value == null) lock.wait();
return value;
}
}
}
现在你可以让 SavedJSON.result
成为一个 MyFuture
,每当有人想要这个值并需要等待时,他们可以简单地调用 SavedJSON.result.get( );
并且集合显然可以是 SavedJSON.result.set(new JSONObject(new String(baos.toByteArray())));
编辑:
这是为了处理您的评论和编辑。
首先:您可能想要传播中断的异常。通常线程会尝试使用中断来“停止”其他线程。您可以在方法上添加 throws 声明、抛出运行时异常或简单地返回空值。
第二:你不应该在 synchronized block 之外设置 value = t。由于各种原因,这有可能失败。您应该删除该行,它看起来很不错。
关于blackberry - 从线程返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5247317/