日期:2014-05-20  浏览次数:20775 次

SWT多线程界面假死问题
这是一个用户文件上传的软件。
在点击了上传按钮之后触发下面的代码:
Java code

new Updater(display, bar, upload).start();
upload.connect(util.getServer().getFtpServer(), 21,LinkHandler.USERNAME, LinkHandler.PASSWORD);
upload.load(task.getClientPath(), task.getServerPath());


这是Updater线程:
Java code

class Updater extends Thread {
    private Display display;
    private ProgressBar bar;
    private LinkHandler handler;

    public Updater(Display display, ProgressBar bar, LinkHandler handler) {
        super();
        this.display = display;
        this.bar = bar;
        this.handler = handler;
    }

    @SuppressWarnings("static-access")
    @Override
    public void run() {
        int i = 0;
        while (handler.getProcess() != 100) {
            final int pro = (int) handler.getProcess();
            System.out.println("第" + (++i) + "次,进度为" + pro + "%");
            try {
                Thread.currentThread().sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("睡了第" + i + "次");
            display.asyncExec(new Runnable() {
                public void run() {
                    if (bar.isDisposed()) {
                        handler.setProcess(100);
                        return;
                    }
                    bar.setSelection(pro);
                    System.out.println("修改完:" + pro);
                }
            });
            System.out.println("第" + i + "次结束");
        }
    }
}



------解决方案--------------------
upload.connect(util.getServer().getFtpServer(), 21,LinkHandler.USERNAME, LinkHandler.PASSWORD);
upload.load(task.getClientPath(), task.getServerPath());

这是真正的上传代码,需要花费时间,把这个也放在额外的线程就不会假死了