诸位童鞋们,我现在在写一个SWT的程序,其中有个功能是读取文件并进行解析,我的想法是用两个线程,一个读文件,一个更新UI,线程间通过Stack交换数据,可现在的问题一旦开始读文件,UI端就会死掉,一直要等文件解析完毕才能正常,加上Thread.sleep也没用。请问这个问题该怎么解决啊?有没有好的方案? 

解决方案 »

  1.   

    给两个代码你 应该有些启发了
    package book.ch3;import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.widgets.Button;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Shell;public class UIThread_1 { public static void main(String args[]) {
    try {
    final Display display = Display.getDefault();
    Shell shell = new Shell(display, SWT.SHELL_TRIM);
    shell.setText("Multi Thread");
    shell.setSize(204, 92);
    final Button button = new Button(shell, SWT.NONE);
    button.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(final SelectionEvent e) {
    try {
    Thread.sleep(10000);
    button.setText("Execution done");
    } catch (InterruptedException e1) {
    e1.printStackTrace();
    }
    }
    });
    button.setText("button");
    button.setBounds(20, 15, 155, 25); shell.open();
    shell.layout();
    while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
    display.sleep();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    package book.ch3;import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.widgets.Button;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Shell;public class UIThread_2 { public static void main(String args[]) {
    try {
    final Display display = Display.getDefault();
    Shell shell = new Shell(display, SWT.SHELL_TRIM);
    shell.setText("Multi Thread");
    shell.setSize(204, 92);
    final Button button = new Button(shell, SWT.NONE);
    button.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(final SelectionEvent e) {
    Thread thread = new Thread() {
    public void run() {
    try {
    Thread.sleep(10000);
    } catch (InterruptedException e1) {
    e1.printStackTrace();
    }
    display.syncExec(new Runnable() {
    public void run() {
    button.setText("Execution Done");
    }
    });
    }
    };
    thread.start();
    }
    });
    button.setText("button");
    button.setBounds(20, 15, 155, 25); shell.open();
    shell.layout();
    while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
    display.sleep();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }}
      

  2.   

    给Stack加个锁,更新UI的那个一直循环,得到stack信息,然后更新到UI上。这样更新UI的线程等待,UI也不会死住