Example usage for java.lang Runnable Runnable

List of usage examples for java.lang Runnable Runnable

Introduction

In this page you can find the example usage for java.lang Runnable Runnable.

Prototype

Runnable

Source Link

Usage

From source file:SplashScreenCreate.java

public static void main(String[] args) {
    final Display display = new Display();
    final int[] count = new int[] { 4 };
    final Image image = new Image(display, 300, 300);
    GC gc = new GC(image);
    gc.setBackground(display.getSystemColor(SWT.COLOR_CYAN));
    gc.fillRectangle(image.getBounds());
    gc.drawText("Splash Screen", 10, 10);
    gc.dispose();//from w  w w  . j ava  2s.  c o m
    final Shell splash = new Shell(SWT.ON_TOP);
    final ProgressBar bar = new ProgressBar(splash, SWT.NONE);
    bar.setMaximum(count[0]);
    Label label = new Label(splash, SWT.NONE);
    label.setImage(image);
    FormLayout layout = new FormLayout();
    splash.setLayout(layout);
    FormData labelData = new FormData();
    labelData.right = new FormAttachment(100, 0);
    labelData.bottom = new FormAttachment(100, 0);
    label.setLayoutData(labelData);
    FormData progressData = new FormData();
    progressData.left = new FormAttachment(0, 5);
    progressData.right = new FormAttachment(100, -5);
    progressData.bottom = new FormAttachment(100, -5);
    bar.setLayoutData(progressData);
    splash.pack();
    Rectangle splashRect = splash.getBounds();
    Rectangle displayRect = display.getBounds();
    int x = (displayRect.width - splashRect.width) / 2;
    int y = (displayRect.height - splashRect.height) / 2;
    splash.setLocation(x, y);
    splash.open();
    display.asyncExec(new Runnable() {
        public void run() {
            Shell[] shells = new Shell[count[0]];
            for (int i = 0; i < count[0]; i++) {
                shells[i] = new Shell(display);
                shells[i].setSize(300, 300);
                shells[i].addListener(SWT.Close, new Listener() {
                    public void handleEvent(Event e) {
                        --count[0];
                    }
                });
                bar.setSelection(i + 1);
                try {
                    Thread.sleep(1000);
                } catch (Throwable e) {
                }
            }
            splash.close();
            image.dispose();
            for (int i = 0; i < count[0]; i++) {
                shells[i].open();
            }
        }
    });
    while (count[0] != 0) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:CreateColorSamplePopup.java

public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Create Popup Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    final JButton button = new JButton("Pick to Change Background");

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            Color initialBackground = button.getBackground();

            final JColorChooser colorChooser = new JColorChooser(initialBackground);
            //        colorChooser.setPreviewPanel(new JPanel());
            final JLabel previewLabel = new JLabel("I Love Swing", JLabel.CENTER);
            previewLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 48));
            colorChooser.setPreviewPanel(previewLabel);
            // Bug workaround
            colorChooser.updateUI();/*from   w  ww  .  ja v a  2 s. c  o m*/

            // For okay button selection, change button background to
            // selected color
            ActionListener okActionListener = new ActionListener() {
                public void actionPerformed(ActionEvent actionEvent) {
                    Color newColor = colorChooser.getColor();
                    if (newColor.equals(button.getForeground())) {
                        System.out.println("Color change rejected");
                    } else {
                        button.setBackground(colorChooser.getColor());
                    }
                }
            };

            // For cancel button selection, change button background to red
            ActionListener cancelActionListener = new ActionListener() {
                public void actionPerformed(ActionEvent actionEvent) {
                    button.setBackground(Color.red);
                }
            };

            final JDialog dialog = JColorChooser.createDialog(null, "Change Button Background", true,
                    colorChooser, okActionListener, cancelActionListener);

            // Wait until current event dispatching completes before showing
            // dialog
            Runnable showDialog = new Runnable() {
                public void run() {
                    dialog.show();
                }
            };
            SwingUtilities.invokeLater(showDialog);
        }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);

    frame.setSize(300, 100);
    frame.setVisible(true);
}

From source file:mulavito.samples.GraphAlgorithmDemo.java

public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        @Override/*from   w w w  .  j  av a  2  s. co m*/
        public void run() {
            GraphAlgorithmDemo main = new GraphAlgorithmDemo();
            main.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    });
}

From source file:com.heliosapm.streams.collector.ds.pool.TestMQPool.java

/**
 * @param args//from w  ww  .  j  a  va2  s  .  c  o m
 */
public static void main(String[] args) {
    try {
        log("Pool Test");
        log(TEST_PROPS);
        JMXHelper.fireUpJMXMPServer(1077);
        final Properties p = Props.strToProps(TEST_PROPS);
        log("Props:" + p);
        final GenericObjectPool<Object> pool = null;//(GenericObjectPool<Object>)PoolConfig.deployPool(p);
        pool.preparePool();
        log("Pool Deployed:" + pool.getNumIdle());
        final List<Object> objects = new ArrayList<Object>();
        for (int i = 0; i < 4; i++) {
            try {
                final Object o = pool.borrowObject();
                log("Borrowed:" + o);
                objects.add(o);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log("Objects:" + objects.size());
        StdInCommandHandler.getInstance().registerCommand("close", new Runnable() {
            public void run() {
                for (Object o : objects) {
                    pool.returnObject(o);
                }
                objects.clear();
                try {
                    pool.close();
                } catch (Exception ex) {
                    ex.printStackTrace(System.err);
                }
            }
        }).run();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

}

From source file:RadialGradientApp.java

public static void main(String... args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new RadialGradientApp().setVisible(true);
        }//from   w  w w. ja va 2  s.c  o  m
    });
}

From source file:AppPackage.Temperature.java

public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Temperature().setVisible(true);
        }//from   ww w  .j a  va  2s  .c o m
    });
}

From source file:com.cloud.test.longrun.PerformanceWithAPI.java

public static void main(String[] args) {

    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String host = "http://localhost";
    int numThreads = 1;

    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = "http://" + iter.next();
        }/*from   w w w  .j  a v a  2 s . co  m*/
        if (arg.equals("-t")) {
            numThreads = Integer.parseInt(iter.next());
        }
        if (arg.equals("-n")) {
            numVM = Integer.parseInt(iter.next());
        }
    }

    final String server = host + ":" + _apiPort + "/";
    final String developerServer = host + ":" + _developerPort + _apiUrl;

    s_logger.info("Starting test in " + numThreads + " thread(s). Each thread is launching " + numVM + " VMs");

    for (int i = 0; i < numThreads; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    String username = null;
                    String singlePrivateIp = null;
                    String singlePublicIp = null;
                    Random ran = new Random();
                    username = Math.abs(ran.nextInt()) + "-user";

                    //Create User
                    User myUser = new User(username, username, server, developerServer);
                    try {
                        myUser.launchUser();
                        myUser.registerUser();
                    } catch (Exception e) {
                        s_logger.warn("Error code: ", e);
                    }

                    if (myUser.getUserId() != null) {
                        s_logger.info("User " + myUser.getUserName()
                                + " was created successfully, starting VM creation");
                        //create VMs for the user
                        for (int i = 0; i < numVM; i++) {
                            //Create a new VM, add it to the list of user's VMs
                            VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
                            myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(),
                                    myUser.getApiKey(), myUser.getSecretKey());
                            myUser.getVirtualMachines().add(myVM);
                            singlePrivateIp = myVM.getPrivateIp();

                            if (singlePrivateIp != null) {
                                s_logger.info(
                                        "VM with private Ip " + singlePrivateIp + " was successfully created");
                            } else {
                                s_logger.info("Problems with VM creation for a user" + myUser.getUserName());
                                break;
                            }

                            //get public IP address for the User            
                            myUser.retrievePublicIp(_zoneId);
                            singlePublicIp = myUser.getPublicIp().get(myUser.getPublicIp().size() - 1);
                            if (singlePublicIp != null) {
                                s_logger.info("Successfully got public Ip " + singlePublicIp + " for user "
                                        + myUser.getUserName());
                            } else {
                                s_logger.info("Problems with getting public Ip address for user"
                                        + myUser.getUserName());
                                break;
                            }

                            //create ForwardProxy rules for user's VMs
                            int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp,
                                    "22", "22");
                            if (responseCode == 500)
                                break;
                        }

                        s_logger.info("Deployment successful..." + numVM
                                + " VMs were created. Waiting for 5 min before performance test");
                        Thread.sleep(300000L); // Wait 

                        //Start performance test for the user
                        s_logger.info("Starting performance test for Guest network that has "
                                + myUser.getPublicIp().size() + " public IP addresses");
                        for (int j = 0; j < myUser.getPublicIp().size(); j++) {
                            s_logger.info("Starting test for user which has "
                                    + myUser.getVirtualMachines().size() + " vms. Public IP for the user is "
                                    + myUser.getPublicIp().get(j) + " , number of retries is " + _retry
                                    + " , private IP address of the machine is"
                                    + myUser.getVirtualMachines().get(j).getPrivateIp());
                            guestNetwork myNetwork = new guestNetwork(myUser.getPublicIp().get(j), _retry);
                            myNetwork.setVirtualMachines(myUser.getVirtualMachines());
                            new Thread(myNetwork).start();
                        }

                    }
                } catch (Exception e) {
                    s_logger.error(e);
                }
            }
        }).start();

    }
}

From source file:AppPackage.humidity.java

public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new humidity().setVisible(true);
        }/* w  w  w  . jav  a  2 s.  co m*/
    });
}

From source file:DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override/*from w ww.  j  av  a2  s.co m*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:SwingThreading.java

public static void main(String... args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            edt = new SwingThreading();
            edt.setVisible(true);//from  w  w w. j  av  a 2s .com

            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                        }
                        edt.incrementLabel();
                    }
                }
            }).start();
        }
    });
}