Java:等待线程结果而不阻塞UI



让我在提问之前先发布一些代码。

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线程的情况下做到这一点?

您可以使用交换工

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 
}

您可以根据调用方

为自定义代码添加一个参数

最新更新