MultiThreading in java, I want both UI and code to execute in parallel

穿精又带淫゛_ 提交于 2019-12-24 17:42:12

问题


I have a JFrame with progress bar and my code which should run it in background showing the progress in progress bar.

I implemented runnable in my Progressbar class and started the thread. But the progress bar frame is not displaying full.. and it gets stuck and it display full after my code is fully executed i.e after main thread close.

I know this is some basic mistake.

public class ProgressScriptUI extends JFrame implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        setTitle("Progressing to Generate DDL Scripts");
        setBounds(400, 250, 850, 400);
        getContentPane().setLayout(null);
        JProgressBar progressBar= new JProgressBar(0,100);
        progressBar.setBounds(200, 100, 500, 20);
        add(progressBar);
        setVisible(true);

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

}

//I am calling the below code in some other class
ProgressScriptUI progress = new ProgressScriptUI();


Thread uiThread = new Thread(progress);                                             
uiThread.start();
oracleValidateOLDorNEW.execute(); //Code that I need to call in back ground

回答1:


All UI code must be executed within the context of the Event Dispatching Thread. This makes it a little tricky to do work in the background while keeping the UI up to date.

Take a look at Concurrency in Swing for suggestions and recommendations for solutions.

Probably the easiest would be to use a SwingWorker which has functionality to publish/process data so that it is synced back to the EDT as well as progress callbacks

You can take a look at

  • JProgressBar won't update
  • Progress Bar Java
  • JProgressBar isn't progressing
  • Show progress during FTP file upload in a java applet

As some examples....




回答2:


I believe you're using Swing for UI. Use SwingWorkers for any long-running task.



来源:https://stackoverflow.com/questions/16272842/multithreading-in-java-i-want-both-ui-and-code-to-execute-in-parallel

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