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:com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

public static void main(String[] args) {
    final ConnectionManager mgr = new ConnectionManager();
    mgr.connFactory = new ConnectionFactory();
    mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
    mgr.connFactory.setPassword("mysql");
    mgr.connFactory.setUsername("mysql");
    mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

    mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
    mgr.pool = mgr.connPoolFactory.createPool();

    final AtomicInteger count = new AtomicInteger(0);

    int threadNum = Runtime.getRuntime().availableProcessors();
    ExecutorService client = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
        client.submit(new Runnable() {
            @Override//ww w .j  a va 2s  .co  m
            public void run() {
                while (true && count.get() < 100) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    Connection connection = null;

                    try {
                        connection = (Connection) mgr.pool.borrowObject();
                        try {

                            int value = count.incrementAndGet();
                            if (value < 100) {
                                String threadName = Thread.currentThread().getName();

                                int activeNum = mgr.pool.getNumActive();
                                int idleNum = mgr.pool.getNumIdle();
                                String content = "ThreadName: " + threadName + "\t SQL: "
                                        + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                        + activeNum + "\t idleNum=" + idleNum;
                                System.out.println(content);
                            }

                        } catch (Exception e) {
                            mgr.pool.invalidateObject(connection);
                            connection = null;
                        } finally {
                            // make sure the object is returned to the pool
                            if (null != connection) {
                                mgr.pool.returnObject(connection);
                            }
                        }
                    } catch (Exception e) {
                        // failed to borrow an object
                    }

                }
            }
        });
    }
}

From source file:gtu._work.ui.RegexReplacer.java

/**
 * Auto-generated main method to display this JFrame
 *//*ww  w  .j a v a  2 s .c  o  m*/
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            RegexReplacer inst = new RegexReplacer();
            inst.setLocationRelativeTo(null);
            gtu.swing.util.JFrameUtil.setVisible(true, inst);
        }
    });
}

From source file:JTextFieldSample.java

public static void main(String args[]) {
    String title = (args.length == 0 ? "TextField Listener Example" : args[0]);
    JFrame frame = new JFrame(title);
    Container content = frame.getContentPane();

    JPanel namePanel = new JPanel(new BorderLayout());
    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField nameTextField = new JTextField();
    nameLabel.setLabelFor(nameTextField);
    namePanel.add(nameLabel, BorderLayout.WEST);
    namePanel.add(nameTextField, BorderLayout.CENTER);
    content.add(namePanel, BorderLayout.NORTH);

    JPanel cityPanel = new JPanel(new BorderLayout());
    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setDisplayedMnemonic(KeyEvent.VK_C);
    JTextField cityTextField = new JTextField();
    cityLabel.setLabelFor(cityTextField);
    cityPanel.add(cityLabel, BorderLayout.WEST);
    cityPanel.add(cityTextField, BorderLayout.CENTER);
    content.add(cityPanel, BorderLayout.SOUTH);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Command: " + actionEvent.getActionCommand());
        }/* ww w. ja v  a  2 s. c o m*/
    };
    nameTextField.setActionCommand("Yo");
    nameTextField.addActionListener(actionListener);
    cityTextField.addActionListener(actionListener);

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            printIt("Pressed", keyEvent);
        }

        public void keyReleased(KeyEvent keyEvent) {
            printIt("Released", keyEvent);
        }

        public void keyTyped(KeyEvent keyEvent) {
            printIt("Typed", keyEvent);
        }

        private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
        }
    };
    nameTextField.addKeyListener(keyListener);
    cityTextField.addKeyListener(keyListener);

    InputVerifier verifier = new InputVerifier() {
        public boolean verify(JComponent input) {
            final JTextComponent source = (JTextComponent) input;
            String text = source.getText();
            if ((text.length() != 0) && !(text.equals("Exit"))) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(source, "Can't leave.", "Error Dialog",
                                JOptionPane.ERROR_MESSAGE);
                    }
                };
                SwingUtilities.invokeLater(runnable);
                return false;
            } else {
                return true;
            }
        }
    };
    nameTextField.setInputVerifier(verifier);
    cityTextField.setInputVerifier(verifier);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type  :   " + typeString + " / ");
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            try {
                System.out.println("Contents: " + source.getText(0, length));
            } catch (BadLocationException badLocationException) {
                System.out.println("Contents: Unknown");
            }
        }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    cityTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 150);
    frame.setVisible(true);
}

From source file:misc.ShapedWindowDemo.java

public static void main(String[] args) {
    // Determine what the GraphicsDevice can support.
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    final boolean isTranslucencySupported = gd.isWindowTranslucencySupported(TRANSLUCENT);

    //If shaped windows aren't supported, exit.
    if (!gd.isWindowTranslucencySupported(PERPIXEL_TRANSPARENT)) {
        System.err.println("Shaped windows are not supported");
        System.exit(0);//from w  ww . j av  a 2s  .com
    }

    //If translucent windows aren't supported, 
    //create an opaque window.
    if (!isTranslucencySupported) {
        System.out.println("Translucency is not supported, creating an opaque window");
    }

    // Create the GUI on the event-dispatching thread
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            ShapedWindowDemo sw = new ShapedWindowDemo();

            // Set the window to 70% translucency, if supported.
            if (isTranslucencySupported) {
                sw.setOpacity(0.7f);
            }

            // Display the window.
            sw.setVisible(true);
        }
    });
}

From source file:com.odap.server.audit.AuditServer.java

public static void main(String[] args) {
    try {/*from w  w  w  . j a  v  a 2 s  .  co  m*/
        logger.info("In main() - " + args[0]);
        args_cpy = args;
        handler = new AuditHandler();
        processor = new AuditEvent.Processor(handler);
        config_handler = new ConfigHandler();
        config_processor = new Config.Processor(config_handler);

        String userName = "root";
        String password = args[1];
        String url = "jdbc:mysql://localhost/auditcloud?zeroDateTimeBehavior=convertToNull";
        keystore_password = args[2];

        DbUtils.loadDriver("com.mysql.jdbc.Driver");

        BoneCPConfig config = new BoneCPConfig(); // create a new configuration object
        config.setJdbcUrl(url); // set the JDBC url
        config.setUsername(userName); // set the username
        config.setPassword(password); // set the password

        connectionPool = new BoneCP(config); // setup the connection pool

        logger.info("Database connection established");

        Configuration conf = HBaseConfiguration.create();
        // conf.set("hbase.zookeeper.quorum", "server1,server2,server3");

        table = new HTable(conf, "sql_audit");
        Runnable simple = new Runnable() {
            public void run() {
                simple(processor, args_cpy[0]);
            }
        };
        Runnable configServer = new Runnable() {
            public void run() {
                configServer(config_processor, args_cpy[0]);
            }
        };

        Runnable heartBeat = new Runnable() {
            public void run() {
                checkHeartBeat();
            }
        };
        new Thread(simple).start();
        new Thread(configServer).start();
        new Thread(heartBeat).start();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:WindowEventDemo.java

public static void main(String[] args) {
    /* Use an appropriate Look and Feel */
    try {/*w  w  w  .j a va2 s .  c  om*/
        // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        // UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    // Schedule a job for the event dispatch thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

From source file:networkmonitor.MainIBMApplicationForm.java

/**
 * Starting point for the  application./*from   w  w w  . j  ava2 s .  c  om*/
 *
 * @param args  ignored.
 */

public static void main(String args[]) {

    //show the java.library.path
    //   System.out.println("java.library.path : " + System.getProperty("java.library.path"));

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {

            MainIBMApplicationForm f = new MainIBMApplicationForm();
            f.setVisible(true); // for visible the frame

        }
    });
}

From source file:com.sun.grizzly.samples.http.embed.GrizzlyEmbedWebServer.java

public static void main(String args[]) throws Exception {
    String path = args[0];/*from   w w  w  .  ja v a  2  s.  c  om*/
    if (args[0] == null || path == null) {
        System.out.println("Invalid static resource path");
        System.exit(-1);
    }

    GrizzlyWebServer ws = new GrizzlyWebServer(path);
    /*        ws.enableJMX(new Management() {
            
    public void registerComponent(Object bean, ObjectName oname, String type) 
    throws Exception{
    Registry.getRegistry().registerComponent(bean,oname,type);
    }
            
            public void unregisterComponent(ObjectName oname) throws Exception{
    Registry.getRegistry().
    unregisterComponent(oname);
            }  
            });
            */

    final Statistics stats = ws.getStatistics();
    stats.startGatheringStatistics();

    ste.scheduleAtFixedRate(new Runnable() {
        public void run() {
            System.out.println(
                    "Current connected users: " + stats.getKeepAliveStatistics().getCountConnections());
            System.out.println(
                    "How many requests since startup:" + stats.getRequestStatistics().getRequestCount());
            System.out.println("How many connection we queued because of all" + "thread were busy: "
                    + stats.getThreadPoolStatistics().getCountQueued());
            System.out.println("Max Open Connection: " + stats.getRequestStatistics().getMaxOpenConnections());

            System.out.println("Request Queued (15min avg): "
                    + stats.getThreadPoolStatistics().getCountQueued15MinuteAverage());
            System.out.println(
                    "Request Queued (total): " + stats.getThreadPoolStatistics().getCountTotalQueued());
            System.out.println("Byte Sent: " + stats.getRequestStatistics().getBytesSent());
            System.out.println("200 Count: " + stats.getRequestStatistics().getCount200());
            System.out.println("404 Count: " + stats.getRequestStatistics().getCount404());

            return;
        }
    }, 0, 10, TimeUnit.SECONDS);
    System.out.println("Grizzly WebServer listening on port 8080");
    ws.start();
}

From source file:com.linkedin.pinotdruidbenchmark.DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(//from  w ww .  j a  v  a 2s.  c  o m
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) {
            int length;
            while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                stringBuilder.append(new String(CHAR_BUFFER, 0, length));
            }
        }
        String query = stringBuilder.toString();
        httpPost.setEntity(new StringEntity(query));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        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:cglabsample.ui.HistogramWindow.java

/**
 * @param args the command line arguments
 *///from  w  w w  . j  a v  a 2 s. co  m
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(HistogramWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(HistogramWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(HistogramWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(HistogramWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new HistogramWindow().setVisible(true);
        }
    });
}