在提问之前,让我先发布一些代码。
public Object returnSomeResult() {
Object o = new Object();
Thread thread = new Thread(this);
thread.start();
return o;
}
public void run() {
// Modify o.
}
因此,方法returnSomeResult
是从UI线程调用的;这会启动另一个线程。现在,我需要等待线程完成计算。同时,我不想阻塞 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 线程的情况下做到这一点?
最佳答案
您可以使用swingworker
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
}
您可以根据调用者为自定义代码添加参数
关于Java:WAITING线程结果而不阻塞UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9270632/