Java/SWT JFace Eclipse/Thread — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:56, 1 июня 2010

Illustrates multithread UI programming issues

/******************************************************************************
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * All right reserved. 
 * 
 * Created on Oct 25, 2003 4:12:32 PM by JACK
 * $Id: PICalculator.java,v 1.1 2003/12/22 12:07:54 jackwind Exp $
 * 
 * visit: http://www.asprise.ru/swt
 *****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
 * Illustrates multithread UI programming issues.
 */
public class PICalculator {
  Display display = new Display();
  Shell shell = new Shell(display);
  Button buttonThread = new Button(shell, SWT.PUSH);
  Button buttonAsyncExec = new Button(shell, SWT.PUSH);
  public PICalculator(boolean asyncExecEnabled) {
    final boolean async = asyncExecEnabled;
    shell.setText("PI Calculator");
    shell.setSize(400, 80);
    Rectangle clientArea = shell.getClientArea();
    buttonThread.setText(
      "Click here to calculate PI  [Non-UI thread UI Update]");
    buttonThread.setBounds(
      clientArea.x,
      clientArea.y,
      clientArea.width,
      clientArea.height / 2);
    buttonThread.addSelectionListener(new SelectionListener() {
      public void widgetDefaultSelected(SelectionEvent e) {
      }
      public void widgetSelected(SelectionEvent e) {
        buttonThread.setText("Calculation in progress ...");
        getTask(buttonThread).start();
      }
    });
    
    buttonAsyncExec.setText("Click here to calculate PI  [asynExec method UI Update]");
    buttonAsyncExec.setBounds(
      clientArea.x,
      clientArea.y + clientArea.height / 2,
      clientArea.width,
      clientArea.height / 2);
    buttonAsyncExec.addSelectionListener(new SelectionListener() {
      public void widgetDefaultSelected(SelectionEvent e) {
      }
      public void widgetSelected(SelectionEvent e) {
        buttonAsyncExec.setText("Calculation in progress ...");
        getTask2(buttonAsyncExec).start();
      }
    });
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  public static void main(String[] args) {
    // new CalculatePI(false);
    new PICalculator(true);
  }
  public Thread getTask(Button button) {
    final Button theButton = button;
    return new Thread() {
      public void run() {
        double pi = calculatePI(9999999);
        theButton.setText("PI = " + pi); // Update UI.
      }
    };
  }
  public Thread getTask2(Button button) {
    final Button theButton = button;
    return new Thread() {
      public void run() {
        final double pi = calculatePI(9999999);
        
        display.asyncExec(new Runnable() {
          public void run() {
            
            // Update UI.
            
            theButton.setText("PI = " + pi); 
            
          }
        });
      }
    };
  }  
  /**
   * Calculate value of PI using Vieta"s formula. For a complete discussion,
   * please visit:
   * http://documents.wolfram.ru/v4/GettingStarted/CalculatingPi.html
   * 
   * @param nestedLevel -
   *            level of nested square roots in Vieta"s formula.
   * @return value of PI
   */
  public static double calculatePI(int nestedLevel) {
    double product = 1;
    double lastSqrtValue = 0;
    for (int i = 0; i < nestedLevel; i++) {
      double sqrt = getNextSqrtValue(lastSqrtValue);
      product *= 0.5 * sqrt;
      lastSqrtValue = sqrt;
    }
    return 2 / product;
  }
  /**
   * Return the square root item value.
   * 
   * @param lastValue -
   *            last square root item value.
   * @return
   */
  public static double getNextSqrtValue(double lastValue) {
    return Math.sqrt(2 + lastValue);
  }
}





SWT and Thread

/******************************************************************************
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * All right reserved. 
 * 
 * Created on Oct 26, 2003 2:45:03 PM by JACK
 * $Id: SyncExecExample.java,v 1.1 2003/12/22 12:07:54 jackwind Exp $
 * 
 * visit: http://www.asprise.ru/swt
 *****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
 * syncExec Example. 
 */
public class SyncExecExample {
  public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    
    final Runnable print = new Runnable() {
      public void run() {
        System.out.println("Print from thread: \t" + Thread.currentThread().getName());
      }
    };
    
    final Thread applicationThread = new Thread("applicationThread") {
      public void run() {
        System.out.println("Hello from thread: \t" + Thread.currentThread().getName());
        display.syncExec(print);
        System.out.println("Bye from thread: \t" + Thread.currentThread().getName());
      }
    };
    
    shell.setText("syncExec Example");
    shell.setSize(300, 100);
    
    Button button = new Button(shell, SWT.CENTER);
    button.setText("Click to start");
    button.setBounds(shell.getClientArea());
    button.addSelectionListener(new SelectionListener() {
      public void widgetDefaultSelected(SelectionEvent e) {
      }
      public void widgetSelected(SelectionEvent e) {
        applicationThread.start();
      }
    });
    
    shell.open();    
    
    
    while(! shell.isDisposed()) {
      if(! display.readAndDispatch()) {// If no more entries in event queue
        display.sleep();
      }
    }
    
    display.dispose();
  
  }
}