Java: wait for thread result without blocking UI?

非 Y 不嫁゛ 提交于 2019-12-25 08:06:16

问题


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.
}

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

I am sure because I am using synchronized(this), it causing UI thread to block. How do i so this without blocking the UI thread ?


回答1:


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 
}

you can add a parameter for custom code depending on the caller



来源:https://stackoverflow.com/questions/9270632/java-wait-for-thread-result-without-blocking-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!