等待线程结果没有阻塞UI

等待线程结果没有阻塞UI

本文介绍了Java:等待线程结果没有阻塞UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let me post some code before I ask question.

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线程被阻止。

So, the method returnSomeResult is called from UI thread; which starts another thread. Now, I need to wait until the thread finishes the calculation. And, meanwhile, I do not want to block UI thread. If I change code as below; the UI thread gets blocked.

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) {
    }
}


$ b b

我相信因为我使用 synchronized(this),它导致UI线程阻塞。我可以使用

you can use the 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:等待线程结果没有阻塞UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:01