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(String name) 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    Thread serverThread = new Thread(new Runnable() {
        @Override//www. ja v  a2 s.co m
        public void run() {
            serverStart();
        }
    });
    serverThread.start();
    Thread clientThread = new Thread(new Runnable() {
        @Override
        public void run() {
            clientStart();
        }
    });
    clientThread.start();
}

From source file:org.echocat.nodoodle.server.Main.java

public static void main(String[] args) {
    final File log4jConfig = new File(System.getProperty("log4j.configuration", "../config/log4j.xml"));
    if (log4jConfig.isFile()) {
        try {//from   ww w  . j  av  a 2  s.  c o  m
            final FileReader reader = new FileReader(log4jConfig);
            try {
                final DOMConfigurator domConfigurator = new DOMConfigurator();
                domConfigurator.doConfigure(reader, getLoggerRepository());
            } finally {
                IOUtils.closeQuietly(reader);
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not configure log4j with " + log4jConfig + ".", e);
        }
    }

    final String applicationName = getApplicationName();
    //System.setSecurityManager(new ServerSecurityManager());
    LOG.info("Starting " + applicationName + "...");

    final File config = new File(
            System.getProperty(Main.class.getPackage().getName() + ".config", "../config/nodoodleServer.xml"));
    final AbstractApplicationContext applicationContext = new FileSystemXmlApplicationContext(config.getPath());
    LOG.info("Starting " + applicationName + "... DONE!");
    Runtime.getRuntime().addShutdownHook(new Thread("destroyer") {
        @Override
        public void run() {
            LOG.info("Stopping " + applicationName + "...");
            applicationContext.stop();
            LOG.info("Stopping " + applicationName + "... DONE!");
        }
    });
}

From source file:com.github.lburgazzoli.sandbox.reactor.ProcessorMain.java

public static void main(String[] args) {
    try {//from  w  w  w  .  ja v  a2 s. c  om
        final Processor<Message> processor = new ProcessorSpec<Message>().dataSupplier(new MessageSupplier())
                .consume(new ThrottlingMessageConsumer(10)).singleThreadedProducer().dataBufferSize(1024).get();

        Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);

        Thread th = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 20; i++) {
                    Operation<Message> op = processor.get();
                    op.get().type = i;
                    op.commit();
                }
            }
        });

        th.start();
        th.join();

        processor.shutdown();

        Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);

    } catch (Exception e) {
        LOGGER.warn("Main Exception", e);
    }
}

From source file:SwingSuspendResume.java

public static void main(String[] args) {
    SwingSuspendResume vsr = new SwingSuspendResume();
    Thread t = new Thread(vsr);
    t.start();/*from ww w  .jav a  2 s.  c  o m*/

    JFrame f = new JFrame();
    f.setContentPane(vsr);
    f.setSize(320, 200);
    f.setVisible(true);
    f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

From source file:info.bitoo.Main.java

public static void main(String[] args)
        throws InterruptedException, IOException, NoSuchAlgorithmException, ClientAdapterException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;// w w w.  j  av  a  2  s . c  om
    try {
        cmd = parser.parse(createCommandLineOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }

    Properties props = readConfiguration(cmd);
    BiToo biToo = new BiToo(props);

    URL torrentURL = null;

    if (cmd.hasOption("f")) {
        String parmValue = cmd.getOptionValue("f");
        String torrentName = parmValue + ".torrent";
        biToo.setTorrent(torrentName);
    } else if (cmd.hasOption("t")) {
        torrentURL = new URL(cmd.getOptionValue("t"));
        biToo.setTorrent(torrentURL);
    } else {
        return;
    }

    try {
        Thread main = new Thread(biToo);
        main.setName("BiToo");
        main.start();

        //wait until thread complete
        main.join();
    } finally {
        biToo.destroy();
    }

    if (biToo.isCompleted()) {
        System.out.println("Download completed");
        System.exit(0);
    } else {
        System.out.println("Download failed");
        System.exit(1);
    }

}

From source file:davmail.DavGateway.java

/**
 * Start the gateway, listen on specified smtp and pop3 ports
 *
 * @param args command line parameter config file path
 *//*from   w ww.  j  av a  2  s  .  c o m*/
public static void main(String[] args) {

    if (args.length >= 1) {
        Settings.setConfigFilePath(args[0]);
    }

    Settings.load();
    DavGatewayTray.init();

    start();

    // server mode: all threads are daemon threads, do not let main stop
    if (Settings.getBooleanProperty("davmail.server")) {
        Runtime.getRuntime().addShutdownHook(new Thread("Shutdown") {
            @Override
            public void run() {
                DavGatewayTray.debug(new BundleMessage("LOG_GATEWAY_INTERRUPTED"));
                DavGateway.stop();
                stopped = true;
            }
        });

        try {
            while (!stopped) {
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            DavGatewayTray.debug(new BundleMessage("LOG_GATEWAY_INTERRUPTED"));
            stop();
            DavGatewayTray.debug(new BundleMessage("LOG_GATEWAY_STOP"));
        }

    }
}

From source file:org.apache.streams.elasticsearch.example.ElasticsearchDirectory.java

public static void main(String[] args) {
    LOGGER.info(StreamsConfigurator.config.toString());

    ElasticsearchDirectory job = new ElasticsearchDirectory();
    (new Thread(job)).start();

}

From source file:com.mebigfatguy.roomstore.RoomStore.java

public static void main(String[] args) {
    Options options = createOptions();/*from   w  w w  . ja  va  2 s  .  c o  m*/

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmdLine = parser.parse(options, args);
        String nickname = cmdLine.getOptionValue(NICK_NAME);
        String server = cmdLine.getOptionValue(IRCSERVER);
        String[] channels = cmdLine.getOptionValues(CHANNELS);
        String[] endPoints = cmdLine.getOptionValues(ENDPOINTS);
        String rf = cmdLine.getOptionValue(RF);

        if ((endPoints == null) || (endPoints.length == 0)) {
            endPoints = new String[] { "127.0.0.1" };
        }

        int replicationFactor;
        try {
            replicationFactor = Integer.parseInt(rf);
        } catch (Exception e) {
            replicationFactor = 1;
        }

        final IRCConnector connector = new IRCConnector(nickname, server, channels);

        Cluster cluster = new Cluster.Builder().addContactPoints(endPoints).build();
        final Session session = cluster.connect();

        CassandraWriter writer = new CassandraWriter(session, replicationFactor);
        connector.setWriter(writer);

        connector.startRecording();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                connector.stopRecording();
                session.close();
            }
        }));

    } catch (ParseException pe) {
        System.out.println("Parse Error on command line options:");
        System.out.println(commandLineRepresentation(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roomstore", options);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:caarray.client.test.full.LoadTest.java

/**
 * @param args//  w  w w. j  a v  a2s  .  c o  m
 */
public static void main(String[] args) {
    List<ApiFacade> apiFacades = new ArrayList<ApiFacade>();
    List<List<ConfigurableTestSuite>> testSuiteCollection = new ArrayList<List<ConfigurableTestSuite>>();
    int numThreads = TestProperties.getNumThreads();
    if (numThreads <= 1) {
        System.out.println(
                "Thread count for load test set to 1 - setting to default count of " + DEFAULT_THREADS);
        numThreads = DEFAULT_THREADS;
    }
    try {
        for (int i = apiFacades.size(); i < numThreads; i++) {
            apiFacades.add(new FullApiFacade());
        }
        for (int i = testSuiteCollection.size(); i < numThreads; i++) {
            List<ConfigurableTestSuite> shortTests = TestMain.getShortTestSuites(apiFacades.get(i));
            List<ConfigurableTestSuite> longTests = TestMain.getLongTestSuites(apiFacades.get(i));
            List<ConfigurableTestSuite> testSuites = new ArrayList<ConfigurableTestSuite>();
            testSuites.addAll(shortTests);
            testSuites.addAll(longTests);
            testSuiteCollection.add(testSuites);
        }
        TestResultReport[] threadReports = new TestResultReport[numThreads];
        for (int i = 0; i < numThreads; i++) {
            threadReports[i] = new TestResultReport();
        }
        Thread[] loadTestThreads = new Thread[numThreads];
        for (int i = 0; i < numThreads; i++) {
            LoadTestThread thread = new LoadTestThread(apiFacades.get(i), testSuiteCollection.get(i),
                    threadReports[i], i);
            loadTestThreads[i] = new Thread(thread);
        }
        System.out.println("Executing load tests for " + numThreads + " threads ...");
        long start = System.currentTimeMillis();
        for (int i = 0; i < numThreads; i++) {
            loadTestThreads[i].start();
        }
        for (int i = 0; i < numThreads; i++) {
            loadTestThreads[i].join();
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("Load tests completed in " + (double) time / (double) 1000 + " seconds.");

        TestResultReport finalReport = new TestResultReport();
        for (TestResultReport report : threadReports) {
            finalReport.merge(report);
        }
        System.out.println("Analyzing load test results ...");
        finalReport.writeLoadTestReports();
    } catch (Throwable t) {
        System.out.println("An exception occured execuitng the load tests: " + t.getClass());
        System.out.println("Test suite aborted.");
        t.printStackTrace();
        log.error("Exception encountered:", t);
    }

}

From source file:com.sm.store.test.LoadTestStoreClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-url", "-store" };
    String[] defaults = new String[] { "2", "10", "localhost:7100", "store" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String url = paras[2];/*  www  .  j a  v a2s .  c  om*/
    String store = paras[3];
    RemoteClientImpl client = new NTRemoteClientImpl(url, null, store);
    for (int i = 0; i < threads; i++) {
        logger.info("start thread # " + i);
        new Thread(new ClientThread(client, times)).start();
    }
    //System.exit(0);
}