Java中的多线程,我希望UI和代码都可以并行执行 [英] MultiThreading in java, I want both UI and code to execute in parallel

查看:247
本文介绍了Java中的多线程,我希望UI和代码都可以并行执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有进度栏的JFrame,我的代码应在后台运行它以显示进度栏的进度.

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

我在Progressbar类中实现了runnable并启动了线程.但是进度条框架没有显示完整..它卡住了,并且在我的代码完全执行后(即在主线程关闭之后)显示为完整.

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

推荐答案

所有UI代码必须在事件调度线程的上下文中执行.这使得在后台进行工作同时保持UI处于最新状态变得有些棘手.

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.

看看 Swing中的并发,以获取有关以下方面的建议解决方案.

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

最简单的方法可能是使用SwingWorker,该功能具有publish/process数据功能,以便将其同步回EDT以及进度回调

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

你可以看看

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

作为一些例子....

这篇关于Java中的多线程,我希望UI和代码都可以并行执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆