Example usage for java.lang Thread start

List of usage examples for java.lang Thread start

Introduction

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

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:ca.ualberta.exemplar.core.Exemplar.java

public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser cli = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "shows this message");
    options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)");
    options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)");

    CommandLine line = null;//from ww  w.  j  a  v  a2s . c o  m

    try {
        line = cli.parse(options, rawArgs);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "malt");

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar", options);
        System.exit(0);
    }

    if (args.length != 2) {
        System.out.println("error: exemplar requires an input file and output file.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar <input> <output>", options);
        System.exit(0);
    }

    File input = new File(args[0]);
    File output = new File(args[1]);

    String benchmarkType = line.getOptionValue("benchmark", "");
    if (!benchmarkType.isEmpty()) {
        if (benchmarkType.equals("binary")) {
            BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName);
            evaluation.runAndTime();
            System.exit(0);
        } else {
            if (benchmarkType.equals("nary")) {
                BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName);
                evaluation.runAndTime();
                System.exit(0);
            } else {
                System.out.println("error: benchmark option has to be either 'binary' or 'nary'.");
                System.exit(0);
            }
        }
    }

    Parser parser = null;
    if (parserName.equals("stanford")) {
        parser = new ParserStanford();
    } else {
        if (parserName.equals("malt")) {
            parser = new ParserMalt();
        } else {
            System.out.println(parserName + " is not a valid parser.");
            System.exit(0);
        }
    }

    System.out.println("Starting EXEMPLAR...");

    RelationExtraction exemplar = null;
    try {
        exemplar = new RelationExtraction(parser);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
    PlainTextReader reader = null;
    reader = new PlainTextReader(inputQueue, input);

    Thread readerThread = new Thread(reader);
    readerThread.start();

    PrintStream statementsOut = null;

    try {
        statementsOut = new PrintStream(output, "UTF-8");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.exit(0);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        System.exit(0);
    }

    statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence");

    while (true) {
        String doc = null;
        try {
            doc = inputQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (doc.isEmpty()) {
            break;
        }

        List<RelationInstance> instances = exemplar.extractRelations(doc);

        for (RelationInstance instance : instances) {

            // Output SUBJ arguments in a separate field, for clarity
            boolean first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("SUBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }

            // Output the original relation
            statementsOut.print("\t" + instance.getOriginalRelation() + "\t");

            // Output the DOBJ arguments, followed by POBJ
            first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("DOBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.startsWith("POBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            statementsOut.print("\t" + instance.getNormalizedRelation());
            statementsOut.print("\t" + instance.getSentence());
            statementsOut.println();
        }
    }

    System.out.println("Done!");
    statementsOut.close();

}

From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA",
            "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY");

    final String endpoint = "sqs.us-west-2.amazonaws.com";
    final String queueName = "image";
    final int producerCount = 10;
    final int consumerCount = 3;
    final int batchSize = 3;
    final int messageSizeByte = 10000;
    final int runTimeMinutes = 100;

    // configure the SQS client with enough connections for all producer and
    // consumer threads
    AmazonSQS sqsClient = new AmazonSQSClient(credentials,
            new ClientConfiguration().withMaxConnections(producerCount + consumerCount));
    sqsClient.setEndpoint(endpoint);/* w  w w . ja v  a2  s.c  o  m*/
    String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();

    // the flag to stop producer, consumer, and monitor threads
    AtomicBoolean stop = new AtomicBoolean(false);

    // start the producers
    final AtomicInteger producedCount = new AtomicInteger();
    Thread[] producers = new Thread[producerCount];
    for (int i = 0; i < producerCount; i++) {
        producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop);
        producers[i].start();
    }

    // start the consumers
    final AtomicInteger consumedCount = new AtomicInteger();
    Thread[] consumers = new Thread[consumerCount];
    for (int i = 0; i < consumerCount; i++) {
        consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop);
        consumers[i].start();
    }

    // start the monitor (thread)
    Thread monitor = new Monitor(producedCount, consumedCount, stop);
    monitor.start();

    // wait for the specified amount of time then stop
    Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES)));
    stop.set(true);

    // join all threads
    for (int i = 0; i < producerCount; i++)
        producers[i].join();

    for (int i = 0; i < consumerCount; i++)
        consumers[i].join();

    monitor.interrupt();
    monitor.join();
}

From source file:jms.Main.java

public static void main(String[] args) throws NamingException, JMSException, FileNotFoundException,
        InterruptedException, ParseException, CloneNotSupportedException {

    Options options = createOptions();/*w  w w.  j  av  a  2  s.com*/

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args, false);

    Histogram latencyHist = Main.metrics.histogram(name(ConsumerThread.class, "global", "consumer", "latency"));
    Meter consumerRate = Main.metrics.meter(name(ConsumerThread.class, "global", "consumer", "rate"));

    if (cmd.hasOption("c")) {
        CONFIG_FILE_PATH = cmd.getOptionValue("c");
    } else {
        CONFIG_FILE_PATH = System.getProperty("user.dir") + "/src/main/resources/client.yaml";
    }

    TestConfiguration config = ConfigReader.parseConfig(CONFIG_FILE_PATH);
    //        System.setProperty("qpid.flow_control_wait_failure", "1500000");
    // Subscribers

    startStatReporting(config.getGlobalConfig());

    int subscriberCount = config.getTopicSubscriberConfigList().size()
            + config.getQueueSubscriberConfigList().size() + config.getDurableSubscriberConfigList().size();
    final List<Thread> threadList = new ArrayList<Thread>(subscriberCount);

    TestTopicSubscriber topicSubscriber;
    for (SubscriberConfig subscriberConfig : config.getTopicSubscriberConfigList()) {
        topicSubscriber = new TestTopicSubscriber();
        topicSubscriber.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(topicSubscriber, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    SimpleJMSConsumer queueReceiver;
    for (SubscriberConfig subscriberConfig : config.getQueueSubscriberConfigList()) {
        queueReceiver = new TestQueueReceiver();
        queueReceiver.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(queueReceiver, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    TestDurableTopicSubscriber durableTopicSubscriber;
    for (SubscriberConfig subscriberConfig : config.getDurableSubscriberConfigList()) {
        durableTopicSubscriber = new TestDurableTopicSubscriber();
        durableTopicSubscriber.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(durableTopicSubscriber, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    // Publishers

    TestTopicPublisher topicPublisher;
    for (PublisherConfig publisherConfig : config.getTopicPublisherList()) {
        topicPublisher = new TestTopicPublisher();
        topicPublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(topicPublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

    TestQueueSender queuePublisher;
    for (PublisherConfig publisherConfig : config.getQueuePublisherConfigList()) {
        queuePublisher = new TestQueueSender();
        queuePublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(queuePublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            log.info("Shutting down test client.");
            slf4jReporter.report();
            csvGaugeReporter.report();
            reporter.report();
            if (null != jmxReporter) {
                jmxReporter.close();
            }

            if (null != csvReporter) {
                csvReporter.report();
                csvReporter.close();
            }

            for (Thread t : threadList) {
                t.interrupt();
            }
        }
    });

    // barrier. wait till all the done
    for (Thread thread : threadList) {
        thread.join();
    }

    log.info("Test Complete!");
}

From source file:com.github.rnewson.couchdb.lucene.Index.java

public static void main(String[] args) throws Exception {
    Utils.LOG.info("indexer started.");
    final Indexer indexer = new Indexer(FSDirectory.getDirectory(Config.INDEX_DIR));
    final Thread thread = new Thread(indexer, "index");
    thread.setDaemon(true);/*from   w w  w. j  ava  2  s  .  c o  m*/
    thread.start();

    final Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
        final String line = scanner.nextLine();
        final JSONObject obj = JSONObject.fromObject(line);
        if (obj.has("type") && obj.has("db")) {
            indexer.setStale(true);
        }
    }
    Utils.LOG.info("indexer stopped.");
}

From source file:org.sourcepit.consul.forwarder.Main.java

public static void main(String[] args) {

    final String dockerUri = "http://192.168.56.101:2375";
    final String consulUri = "http://192.168.56.101:8500";

    final int fetchConsulStateInterval = 30;
    final int fetchDockerStateInterval = 30;
    final int dispatchItemsInterval = 2;
    final int requestDockerStateDelay = 5;

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(10);
    final HttpClient httpClient = HttpClients.createMinimal(connManager);

    final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>();

    final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) {
        @Override/*from   w  w w . ja v a  2  s. c  om*/
        protected void doHandle(JsonObject consulState) {
            final JsonObject item = createItem("ConsulState", consulState);
            LOG.debug(item.toString());
            queue.add(item);
        }

    };

    final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) {
        @Override
        protected void doHandle(JsonArray dockerState) {
            final JsonObject item = createItem("DockerState", dockerState);
            LOG.debug(item.toString());
            queue.add(item);
        }
    };

    final ConsulForwarderState forwarderState = new ConsulForwarderState();

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) {
        @Override
        protected void handleDockerState(JsonArray dockerState) {
            forwarderState.applyDockerState(dockerState);
        }

        @Override
        protected void handleDockerEvents(JsonArray dockerEvents) {
            // trigger docker state update
            scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS);
        }

        @Override
        protected void handleConsulState(JsonObject consulState) {
            forwarderState.applyConsulState(consulState);
        }
    }, 0, dispatchItemsInterval, TimeUnit.SECONDS);

    final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(createItem("DockerEvent", event));
        }
    };

    final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };
    eventObserverThread.start();
}

From source file:za.co.taung.httpdotserver.main.HttpDotServer.java

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

    LOG.info("Initialise server");

    // The parameter is the Port to listen on. Default is 8080. 
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }/*from w w  w  . ja va  2  s.  c om*/

    // Set up the HTTP protocol processor.
    HttpProcessor httpProcessor = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("HttpDotServer/1.1")).add(new ResponseContent())
            .add(new ResponseConnControl()).build();

    // Set up request handler. This is the method that generates SVG. 
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new Dot2SVGHandler());

    // Set up the HTTP service.
    HttpService httpService = new HttpService(httpProcessor, reqistry);

    // Set up SSL if listening on 8443 for https.
    SSLServerSocketFactory serverSocketFactory = null;
    if (port == 8443) {
        // Get the location of the keystore secrets.
        ClassLoader cl = HttpDotServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            LOG.error("Keystore not found");
            System.exit(1);
        }
        // Load the secret into a keystore and manage the key material.
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        // Prepare the socket factory for use by the RequestListenerThread.
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        serverSocketFactory = sslcontext.getServerSocketFactory();
    }

    LOG.debug("Start the RequestListenerThread");
    Thread thread = new RequestListenerThread(port, httpService, serverSocketFactory);
    thread.setDaemon(false);
    thread.start();
}

From source file:com.meidusa.venus.benchmark.FileLineData.java

public static void main(String[] args) throws Exception {
    final FileLineData mapping = new FileLineData();
    mapping.setFile(new File("./role.txt"));
    mapping.init();/*www.ja v a  2s .c  o  m*/
    List<Thread> list = new ArrayList<Thread>();
    long start = TimeUtil.currentTimeMillis();
    for (int j = 0; j < 1; j++) {
        Thread thread = new Thread() {
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    System.out.println(mapping.nextData());
                }
            }
        };
        list.add(thread);
        thread.start();
    }

    for (int i = 0; i < list.size(); i++) {
        list.get(i).join();
    }

    System.out.println("time=" + (TimeUtil.currentTimeMillis() - start));
}

From source file:ExecDemoLs.java

public static void main(String argv[]) throws IOException {

    final Process p; // Process tracks one external native process
    BufferedReader is; // reader for output of process
    String line;/*from  w w w. j  av a 2s.c om*/

    p = Runtime.getRuntime().exec(PROGRAM);

    // Optional: start a thread to wait for the process to terminate.
    // Don't just wait in main line, but here set a "done" flag and
    // use that to control the main reading loop below.
    Thread waiter = new Thread() {
        public void run() {
            try {
                p.waitFor();
            } catch (InterruptedException ex) {
                // OK, just quit.
                return;
            }
            System.out.println("Program terminated!");
            done = true;
        }
    };
    waiter.start();

    // getInputStream gives an Input stream connected to
    // the process p's standard output (and vice versa). We use
    // that to construct a BufferedReader so we can readLine() it.
    is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while (!done && ((line = is.readLine()) != null))
        System.out.println(line);

    return;
}

From source file:com.salaboy.rolo.server.RoloCommandServer.java

public static void main(String[] args) throws Exception {
    final Weld weld = new Weld();

    WeldContainer container = weld.initialize();

    RoloCommandServer roloCommandServer = container.instance().select(RoloCommandServer.class).get();

    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("t", true, "sensors latency");
    options.addOption("ip", true, "host");
    options.addOption("port", true, "port");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    String sensorLatency = cmd.getOptionValue("t");
    if (sensorLatency == null) {
        System.out.println(" The Default Latency will be used: " + defaultLatency);
    } else {/*from  w  w w  .  j a v a 2  s  .co  m*/
        System.out.println(" The Latency will be set to: " + sensorLatency);
        defaultLatency = new Long(sensorLatency);
    }

    String ip = cmd.getOptionValue("ip");
    if (ip == null) {
        System.out.println(" The Default IP will be used: 127.0.0.1");
        roloCommandServer.setHost("127.0.0.1");

    } else {
        System.out.println(" The IP will be set to: " + ip);
        roloCommandServer.setHost(ip);
    }

    String port = cmd.getOptionValue("port");
    if (port == null) {
        System.out.println(" The Default Port will be used: 5445");
        roloCommandServer.setPort(5445);

    } else {
        System.out.println(" The Port will be set to: " + port);
        roloCommandServer.setPort(Integer.parseInt(port));
    }

    System.out.println("Starting Server Rolo ...");

    Thread thread = new Thread(roloCommandServer);
    thread.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            System.out.println("Shutdown Hook is running !");
            readSensors = false;
            weld.shutdown();
        }
    });

}

From source file:jp.mamesoft.mailsocketchat.Mailsocketchat.java

public static void main(String argv[]) {
    System.out.println("MailSocketChat Ver." + version);
    if (argv.length != 6) {
        System.out.println(/*w w  w  .  j  ava2  s .  c om*/
                "ERROR! ? <?URL> <???> <GMail??> <GMail> <(Simple???Normal???All)> <????(Subject???Text)> ???????");
        System.exit(0);
    }

    TimerTask newversion = new NewVersion();
    Timer timer = new Timer();
    timer.schedule(newversion, 0, 6 * 60 * 60 * 1000); //6??????

    chat_url = argv[0];
    chat_name = argv[1];
    mail_user = argv[2];
    mail_pass = argv[3];

    if (argv[4].equals("Simple")) {
        logformat = "simple";
    } else if (argv[4].equals("Normal")) {
        logformat = "normal";
    } else if (argv[4].equals("All")) {
        logformat = "all";
    } else {
        System.out.println(
                "ERROR! (5)???????Simple???Normal???All???????");
        System.exit(0);
    }

    if (argv[5].equals("Subject")) {
        subjectname = true;
    } else if (argv[5].equals("Text")) {
        subjectname = false;
    } else {
        System.out.println(
                "ERROR! ????(6)???????Subject???Text???????");
        System.exit(0);
    }

    try {
        Properties headers = new Properties();
        headers.setProperty("user-agent", "MailSocketChat/" + version + " (" + osName + " " + osVer + ") Java/"
                + javaver + " (Mamesoft Web)");
        socket = new SocketIO(chat_url, headers);
        socket.connect(new IOCallback() {
            @Override
            public void onMessage(JSONObject json, IOAcknowledge ack) {
                try {
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMessage(String data, IOAcknowledge ack) {
            }

            @Override
            public void onError(SocketIOException socketIOException) {
                System.out.println("??????");
                System.err.println(socketIOException);
                System.exit(0);
            }

            @Override
            public void onDisconnect() {
                System.out.println("???????");
                System.exit(0);
            }

            @Override
            public void onConnect() {
                socket.emit("register", new JSONObject().put("mode", "client").put("lastid", 1));
                System.out.println("SocketChat?????");
                Thread mail = new Mail();
                mail.start();
            }

            @Override
            public void on(String event, IOAcknowledge ack, Object... args) {
                if (event.equals("log")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    Logperse(jsondata);
                }
                if (event.equals("init")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    JSONArray logs = jsondata.getJSONArray("logs");
                    for (int i = logs.length() - 1; i >= 0; i--) {
                        JSONObject log = logs.getJSONObject(i);
                        Logperse(log);
                    }
                    socket.emit("inout", new JSONObject().put("name", chat_name));
                }
                if (event.equals("result")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    System.out.println(jsondata);
                }
                if (event.equals("users")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    JSONArray users = jsondata.getJSONArray("users");
                    for (int i = 0; i < users.length(); i++) {
                        JSONObject user = users.getJSONObject(i);
                        userchange(user);
                    }
                }
                if (event.equals("newuser")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    userchange(jsondata);
                }
                if (event.equals("inout")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    userchange(jsondata);
                }
                if (event.equals("deluser")) {
                    Integer id = (Integer) args[0];
                    if (users.containsKey(id)) {
                        users.remove(id);
                    }
                    if (roms.containsKey(id)) {
                        roms.remove(id);
                    }

                }
                if (event.equals("userinfo")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    if (jsondata.getBoolean("rom")) {
                        in = false;
                    } else {
                        in = true;
                    }
                }
            }
        });

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
        System.out.println("URL????????");
        return;
    }
}