[英]Java: wait for thread result without blocking UI?
在问问题之前,让我发布一些代码。
public Object returnSomeResult() {
Object o = new Object();
Thread thread = new Thread(this);
thread.start();
return o;
}
public void run() {
// Modify o.
}
因此,从UI线程调用方法returnSomeResult
; 这将启动另一个线程。 现在,我需要等到线程完成计算。 同时,我不想阻止UI线程。 如果我更改代码如下: UI线程被阻止。
public Object returnSomeResult() {
Object o = new Object();
Thread thread = new Thread(this);
thread.start();
try {
synchronized(this) {
wait();
}
catch(Exception e) {
}
return o;
}
public void run() {
// Modify o.
try {
synchronized(this) {
notify();
}
catch(Exception e) {
}
}
我确定是因为我正在使用synchronized(this)
,它导致UI线程阻塞。 我如何在不阻塞UI线程的情况下这样做?
你可以用摇摆工
public SwingWorker<Object,Void> returnSomeResult() {
SwingWorker<Object,Void> w = new SwingWorker(){
protected Void doInBackground(){
Object o;
//compute o in background thread
return o;
}
protected void done(){
Object o=get();
//do something with o in the event thread
}
}
w.execute();
return w;//if you want to do something with it
}
您可以根据调用者添加自定义代码的参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.