Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

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

Prototype

public Thread() 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:GenericClient.java

public static void main(String[] args) throws IOException {
    try {//  w w w.jav  a 2 s  . c o  m
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}

From source file:com.msopentech.ThaliClient.ProxyDesktop.java

public static void main(String[] rgs) throws InterruptedException, URISyntaxException, IOException {

    final ProxyDesktop instance = new ProxyDesktop();
    try {/*www  . ja va2  s  .  c o m*/
        instance.initialize();
    } catch (RuntimeException e) {
        System.out.println(e);
    }

    // Attempt to launch the default browser to our page
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(new URI("http://localhost:" + localWebserverPort));
    }

    // Register to shutdown the server properly from a sigterm
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            instance.shutdown();
        }
    });

    // Let user press enter to kill the console session
    Console console = System.console();
    if (console != null) {
        console.format("\nPress ENTER to exit.\n");
        console.readLine();
        instance.shutdown();
    } else {
        // Don't exit on your own when running without a console (debugging in an IDE).
        while (true) {
            Thread.sleep(500);
        }
    }
}

From source file:ca.uqac.info.trace.TraceGenerator.java

public static void main(String[] args) {
    // Parse command line arguments
    Options options = setupOptions();// www  . j a  v  a2 s  . c  o m
    CommandLine c_line = setupCommandLine(args, options);
    int verbosity = 0, max_events = 1000000;

    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    String generator_name = "simplerandom";
    if (c_line.hasOption("g")) {
        generator_name = c_line.getOptionValue("generator");
    }
    long time_per_msg = 1000;
    if (c_line.hasOption("i")) {
        time_per_msg = Integer.parseInt(c_line.getOptionValue("i"));
    }
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (c_line.hasOption("e")) {
        max_events = Integer.parseInt(c_line.getOptionValue("e"));
    }
    String feeder_params = "";
    if (c_line.hasOption("parameters")) {
        feeder_params = c_line.getOptionValue("parameters");
    }
    MessageFeeder mf = instantiateFeeder(generator_name, feeder_params);
    if (mf == null) {
        System.err.println("Unrecognized feeder name");
        System.exit(ERR_ARGUMENTS);
    }
    // Trap Ctrl-C to send EOT before shutting down
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            char EOT = 4;
            System.out.print(EOT);
        }
    });
    for (int num_events = 0; mf.hasNext() && num_events < max_events; num_events++) {
        long time_begin = System.nanoTime();
        String message = mf.next();
        StringBuilder out = new StringBuilder();
        out.append(message);
        System.out.print(out.toString());
        long time_end = System.nanoTime();
        long duration = time_per_msg - (long) ((time_end - time_begin) / 1000000f);
        if (duration > 0) {
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {
            }
        }
        if (verbosity > 0) {
            System.err.print("\r" + num_events + " " + duration + "/" + time_per_msg);
        }
    }
}

From source file:com.apipulse.bastion.Main.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    log.info("Bastion starting. Loading chains");
    final File dir = new File("etc/chains");

    final LinkedList<ActorRef> chains = new LinkedList<ActorRef>();
    for (File file : dir.listFiles()) {
        if (!file.getName().startsWith(".") && file.getName().endsWith(".yaml")) {
            log.info("Loading chain: " + file.getName());
            ChainConfig config = new ChainConfig(IOUtils.toString(new FileReader(file)));
            ActorRef ref = BastionActors.getInstance().initChain(config.getName(),
                    Class.forName(config.getQualifiedClass()));
            Iterator<StageConfig> iterator = config.getStages().iterator();
            while (iterator.hasNext())
                ref.tell(iterator.next(), null);
            chains.add(ref);/*from  w w  w  .  ja  v a 2s.  c o  m*/
        }
    }
    SpringApplication app = new SpringApplication();
    HashSet<Object> objects = new HashSet<Object>();
    objects.add(ApiController.class);
    final ConfigurableApplicationContext context = app.run(ApiController.class, args);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                log.info("Bastion shutting down");
                Iterator<ActorRef> iterator = chains.iterator();
                while (iterator.hasNext())
                    iterator.next().tell(new StopMessage(), null);
                Thread.sleep(2000);
                context.stop();
                log.info("Bastion shutdown complete");
            } catch (Exception e) {
            }
        }
    });
}

From source file:com.ok2c.lightmtp.examples.LocalMailServerTransportExample.java

public static void main(final String[] args) throws Exception {
    File workingDir = new File(".");
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    final MailServerTransport mta = new LocalMailServerTransport(workingDir, config);

    InetSocketAddress sockaddress = new InetSocketAddress("localhost", 2525);

    InetAddressRange iprange = new InetAddressRange(InetAddress.getByName("127.0.0.0"), 8);

    mta.start(new DefaultIdGenerator(), new MyRemoteAddressValidator(iprange), new MyEnvelopValidator(),
            new MyDeliveryHandler());
    mta.listen(sockaddress);/* w w w .  jav a 2  s.c o m*/

    System.out.println("LMTP server listening on " + sockaddress);

    Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                mta.shutdown();
            } catch (IOException ex) {
                mta.forceShutdown();
            }
        }

    });
}

From source file:Graph_with_jframe_and_arduino.java

public static void main(String[] args) {

    // create and configure the window
    JFrame window = new JFrame();
    window.setTitle("Sensor Graph GUI");
    window.setSize(600, 400);/*from   w w w .jav  a  2 s.  c o m*/
    window.setLayout(new BorderLayout());
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create a drop-down box and connect button, then place them at the top of the window
    JComboBox<String> portList_combobox = new JComboBox<String>();
    Dimension d = new Dimension(300, 100);
    portList_combobox.setSize(d);
    JButton connectButton = new JButton("Connect");
    JPanel topPanel = new JPanel();
    topPanel.add(portList_combobox);
    topPanel.add(connectButton);
    window.add(topPanel, BorderLayout.NORTH);
    //pause button
    JButton Pause_btn = new JButton("Start");

    // populate the drop-down box
    SerialPort[] portNames;
    portNames = SerialPort.getCommPorts();
    //check for new port available
    Thread thread_port = new Thread() {
        @Override
        public void run() {
            while (true) {
                SerialPort[] sp = SerialPort.getCommPorts();
                if (sp.length > 0) {
                    for (SerialPort sp_name : sp) {
                        int l = portList_combobox.getItemCount(), i;
                        for (i = 0; i < l; i++) {
                            //check port name already exist or not
                            if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) {
                                break;
                            }
                        }
                        if (i == l) {
                            portList_combobox.addItem(sp_name.getSystemPortName());
                        }

                    }

                } else {
                    portList_combobox.removeAllItems();

                }
                portList_combobox.repaint();

            }

        }

    };
    thread_port.start();
    for (SerialPort sp_name : portNames)
        portList_combobox.addItem(sp_name.getSystemPortName());

    //for(int i = 0; i < portNames.length; i++)
    //   portList.addItem(portNames[i].getSystemPortName());

    // create the line graph
    XYSeries series = new XYSeries("line 1");
    XYSeries series2 = new XYSeries("line 2");
    XYSeries series3 = new XYSeries("line 3");
    XYSeries series4 = new XYSeries("line 4");
    for (int i = 0; i < 100; i++) {
        series.add(x, 0);
        series2.add(x, 0);
        series3.add(x, 0);
        series4.add(x, 10);
        x++;
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(series2);
    XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(series3);
    dataset2.addSeries(series4);

    //create jfree chart
    JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading",
            dataset);
    JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2",
            dataset2);

    //color render for chart 1
    XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer();
    r1.setSeriesPaint(0, Color.RED);
    r1.setSeriesPaint(1, Color.GREEN);
    r1.setSeriesShapesVisible(0, false);
    r1.setSeriesShapesVisible(1, false);

    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(0, r1);
    plot.setRenderer(1, r1);

    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.blue);

    //color render for chart 2
    XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer();
    r2.setSeriesPaint(0, Color.BLUE);
    r2.setSeriesPaint(1, Color.ORANGE);
    r2.setSeriesShapesVisible(0, false);
    r2.setSeriesShapesVisible(1, false);

    XYPlot plot2 = chart2.getXYPlot();
    plot2.setRenderer(0, r2);
    plot2.setRenderer(1, r2);

    ChartPanel cp = new ChartPanel(chart);
    ChartPanel cp2 = new ChartPanel(chart2);

    //multiple graph container
    JPanel graph_container = new JPanel();
    graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS));
    graph_container.add(cp);
    graph_container.add(cp2);

    //add chart panel in main window
    window.add(graph_container, BorderLayout.CENTER);
    //window.add(cp2, BorderLayout.WEST);

    window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE);
    Pause_btn.setEnabled(false);
    //pause btn action
    Pause_btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (Pause_btn.getText().equalsIgnoreCase("Pause")) {

                if (chosenPort.isOpen()) {
                    try {
                        Output.write(0);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Start");
            } else {
                if (chosenPort.isOpen()) {
                    try {
                        Output.write(1);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Pause");
            }
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // configure the connect button and use another thread to listen for data
    connectButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (connectButton.getText().equals("Connect")) {
                // attempt to connect to the serial port
                chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString());
                chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
                if (chosenPort.openPort()) {
                    Output = chosenPort.getOutputStream();
                    connectButton.setText("Disconnect");
                    Pause_btn.setEnabled(true);
                    portList_combobox.setEnabled(false);
                }

                // create a new thread that listens for incoming text and populates the graph
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        Scanner scanner = new Scanner(chosenPort.getInputStream());
                        while (scanner.hasNextLine()) {
                            try {
                                String line = scanner.nextLine();
                                int number = Integer.parseInt(line);
                                series.add(x, number);
                                series2.add(x, number / 2);
                                series3.add(x, number / 1.5);
                                series4.add(x, number / 5);

                                if (x > 100) {
                                    series.remove(0);
                                    series2.remove(0);
                                    series3.remove(0);
                                    series4.remove(0);
                                }

                                x++;
                                window.repaint();
                            } catch (Exception e) {
                            }
                        }
                        scanner.close();
                    }
                };
                thread.start();
            } else {
                // disconnect from the serial port
                chosenPort.closePort();
                portList_combobox.setEnabled(true);
                Pause_btn.setEnabled(false);
                connectButton.setText("Connect");

            }
        }
    });

    // show the window
    window.setVisible(true);
}

From source file:com.callidusrobotics.irc.NaNoBot.java

public static void main(final String[] args)
        throws FileNotFoundException, IOException, NickAlreadyInUseException, IrcException {
    if (args.length > 0 && "--version".equals(args[0])) {
        System.out.println("NaNoBot version: " + getImplementationVersion());
        System.exit(0);/*w w w. j  a  va  2 s  .  c o  m*/
    }

    final String fileName = args.length > 0 ? args[0] : "./NaNoBot.properties";
    final Properties properties = new Properties();
    properties.load(new FileInputStream(new File(fileName)));

    final NaNoBot naNoBot = new NaNoBot(properties);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            naNoBot.shutdown();
        }
    });

    naNoBot.run();
}

From source file:de.saly.elasticsearch.importer.imap.IMAPImporterCl.java

public static void main(String[] args) throws Exception {

    if (args.length < 1) {
        System.out.println("Usage: IMAPImporterC [-e] <config-file>");
        System.exit(-1);//from  www . j a v a2  s  .c  o m
    }

    String configFile = null;
    boolean embedded = false;

    if (args.length == 1) {
        configFile = args[0];
    }

    if (args.length == 2) {

        embedded = "-e".equals(args[0]);
        configFile = args[1];
    }

    System.out.println("Config File: " + configFile);
    System.out.println("Embedded: " + embedded);

    final Thread mainThread = Thread.currentThread();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            System.out.println("Will shutdown ...");

            IMAPImporterCl.stop();

            try {
                mainThread.join();
                System.out.println("Shudown done");
            } catch (InterruptedException e) {

            }
        }
    });

    start(configFile, embedded);
}

From source file:com.serotonin.m2m2.Main.java

/**
 *
 * @param args/*from   w  w w . ja va 2s .co  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Providers.add(ICoreLicense.class, new CoreLicenseDefinition());

    Common.MA_HOME = System.getProperty("ma.home");
    Common.M2M2_HOME = Common.MA_HOME;

    new File(Common.MA_HOME, "RESTART").delete();

    Common.envProps = new ReloadingProperties("env");

    openZipFiles();
    ClassLoader moduleClassLoader = loadModules();

    Lifecycle lifecycle = new Lifecycle();
    Providers.add(ILifecycle.class, lifecycle);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ((ILifecycle) Providers.get(ILifecycle.class)).terminate();
        }
    });
    try {
        lifecycle.initialize(moduleClassLoader);
        if ((!GraphicsEnvironment.isHeadless()) && (Desktop.isDesktopSupported())
                && (Common.envProps.getBoolean("web.openBrowserOnStartup"))) {
            Desktop.getDesktop().browse(new URI(new StringBuilder().append("http://localhost:")
                    .append(Common.envProps.getInt("web.port", 8088)).toString()));
        }
    } catch (Exception e) {
        LOG.error("Error during initialization", e);
        lifecycle.terminate();
    }
}

From source file:at.ac.tuwien.dsg.comot.m.adapter.Main.java

public static void main(String[] args) {

    Options options = createOptions();//from w  ww. ja  va2 s  .  c o m

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("mh") && cmd.hasOption("ih") && cmd.hasOption("ip")) {

            Integer infoPort = null;

            try {
                infoPort = new Integer(cmd.getOptionValue("ip"));
            } catch (NumberFormatException e) {
                LOG.warn("infoPort must be a number");
                showHelp(options);
            }

            AppContextAdapter.setBrokerHost(cmd.getOptionValue("mh"));
            AppContextAdapter.setInfoHost(cmd.getOptionValue("ih"));
            AppContextAdapter.setInfoPort(infoPort);

            context = new AnnotationConfigApplicationContext(AppContextAdapter.class);

            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    if (context != null) {
                        context.close();
                    }
                }
            });

            if (cmd.hasOption("m") || cmd.hasOption("r") || cmd.hasOption("s")) {

                Manager manager = context.getBean(EpsAdapterManager.class);
                String serviceId = getServiceInstanceId();
                String participantId = context.getBean(InfoClient.class).getOsuInstanceByServiceId(serviceId)
                        .getId();

                if (cmd.hasOption("m")) {

                    Monitoring processor = context.getBean(Monitoring.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("r")) {

                    Control processor = context.getBean(Control.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("s")) {

                    Deployment processor = context.getBean(Deployment.class);
                    manager.start(participantId, processor);
                }

            } else {
                LOG.warn("No adapter type specified");
                showHelp(options);
            }
        } else {
            LOG.warn("Required parameters were not specified.");
            showHelp(options);
        }
    } catch (Exception e) {
        LOG.error("{}", e);
        showHelp(options);
    }
}