Java: wait for thread result without blocking UI?

2019-09-06 16:17发布

问题:

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