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: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();
        }/*www .jav  a2  s .  com*/
        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:de.hadesrofl.mqtt_client.App.java

public static void main(String[] args) {
    String cf = "";
    if (args.length > 0) {
        cf = args[0];/*from   www .  ja  v a  2 s  . com*/
    } else {
        cf = "config.json";
    }
    JSONObject config = JsonReader.readFile(cf);
    if (config == null)
        System.exit(-1);
    JSONObject broker = config.getJSONObject("broker");
    JSONObject topics = broker.getJSONObject("topics");
    Database db = null;
    try {
        JSONObject database = config.getJSONObject("database");
        db = new Database(database.getString("dbHost"), database.getString("dbPort"),
                database.getString("dbName"), database.getString("dbUser"), database.getString("dbPass"));
    } catch (JSONException e) {
        System.err.println("No database mentioned in config file");
    }
    List<ClientMqtt> clients = new ArrayList<ClientMqtt>();
    List<Thread> clientThreads = new ArrayList<Thread>();
    for (String topic : topics.keySet()) {
        ClientMqtt client = null;
        if (db == null) {
            client = new ClientMqtt(broker.getString("address"), broker.getInt("port"),
                    topics.getString(topic));
        } else {
            client = new ClientMqtt(broker.getString("address"), broker.getInt("port"), topics.getString(topic),
                    db);
        }
        Thread clientThread = new Thread(client);
        client.setSubscriber(broker.getBoolean("subscribe"));
        clients.add(client);
        clientThreads.add(clientThread);
        clientThread.start();
        // Need to wait a bit as the client needs to connect first
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.err.println("Thread can't sleep, need to take painkillers");
        }
        client.publishMessage("Ground control to Major Tom", 1);
    }
}

From source file:playground.Application.java

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

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("playground");
    DispatcherHandler dispatcherHandler = new DispatcherHandler();
    dispatcherHandler.setApplicationContext(context);

    HttpServer server = new ReactorHttpServer();
    server.setPort(8080);/*from   w w w .  jav a  2  s  . c om*/
    server.setHandler(dispatcherHandler);
    server.afterPropertiesSet();
    server.start();

    CompletableFuture<Void> stop = new CompletableFuture<>();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        stop.complete(null);
    }));

    synchronized (stop) {
        stop.wait();
    }

}

From source file:SwingThreading.java

public static void main(String... args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            edt = new SwingThreading();
            edt.setVisible(true);/* w ww.ja  v a2 s .c o m*/

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

From source file:com.autodomum.example.Example1.java

public static void main(String[] args) throws Exception {
    final ConfigurableApplicationContext context = SpringApplication.run(Example1.class, args);
    final JsonLampDao jsonLampDao = context.getBean(JsonLampDao.class);
    final EventComponent eventComponent = context.getBean(EventComponent.class);
    final EventContext eventContext = context.getBean(EventContext.class);
    final TelldusComponent telldusComponent = context.getBean(TelldusComponent.class);
    final NashornScriptComponent nashornScriptComponent = context.getBean(NashornScriptComponent.class);

    final Thread eventComponentThread = new Thread(eventComponent);
    eventComponentThread.setDaemon(true);
    eventComponentThread.setPriority(Thread.MIN_PRIORITY);
    eventComponentThread.setName("EventComponent");
    eventComponentThread.start();/*from   ww w  .j av  a  2  s .c  o  m*/

    // Coordinates of Stockholm
    eventContext.setCoordinate(new Coordinate(18.063240d, 59.334591d));

    eventComponent.updateEventContext();
    eventComponent.register(LampStateChangedEvent.class, telldusComponent);

    final Thread telldusComponentThread = new Thread(telldusComponent);
    telldusComponentThread.setDaemon(true);
    telldusComponentThread.setPriority(Thread.MIN_PRIORITY);
    telldusComponentThread.setName("Telldus");
    telldusComponentThread.start();

    try (InputStream inputStream = Example1.class.getResourceAsStream("/lamps.json")) {
        jsonLampDao.load(inputStream);
    }

    try (InputStream inputStream = Example1.class.getResourceAsStream("/ai.js")) {
        nashornScriptComponent.replaceScript(inputStream);
    }
}

From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerDeterministicUnitTest.java

public static void main(String args[]) throws ACIDException, IOException, AsterixException {
    //prepare configuration file
    File cwd = new File(System.getProperty("user.dir"));
    File asterixdbDir = cwd.getParentFile();
    File srcFile = new File(asterixdbDir.getAbsoluteFile(),
            "asterix-app/src/main/resources/asterix-build-configuration.xml");
    File destFile = new File(cwd, "target/classes/asterix-configuration.xml");
    FileUtils.copyFile(srcFile, destFile);

    //initialize controller thread
    String requestFileName = new String(
            "src/main/java/edu/uci/ics/asterix/transaction/management/service/locking/LockRequestFile");
    Thread t = new Thread(new LockRequestController(requestFileName));
    t.start();//w w w .  j a  v a  2  s . c o m
}

From source file:com.clicktravel.cheddar.server.rest.application.RestApplication.java

/**
 * Starts the RestServer to listen on the given port and address combination
 *
 * @param args String arguments, {@code [context [service-port [status-port [bind-address] ] ] ]} where
 *            <ul>//from  w  ww  .j av  a 2 s.  c om
 *            <li>{@code context} - Name of application, defaults to {@code UNKNOWN}</li>
 *            <li>{@code service-port} - Port number for REST service endpoints, defaults to {@code 8080}</li>
 *            <li>{@code status-port} - Port number for REST status endpoints ({@code /status} and
 *            {@code /status/healthCheck}), defaults to {@code service-port + 100}</li>
 *            <li>{@code bind-address} - Local IP address to bind server to, defaults to {@code 0.0.0.0}</li>
 *            </ul>
 *
 * @throws Exception
 */
public static void main(final String... args) {
    final String context = args.length > 0 ? args[0] : "UNKNOWN";
    final int servicePort = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    final int statusPort = args.length > 2 ? Integer.parseInt(args[2]) : servicePort + 100;
    final String bindAddress = args.length > 3 ? args[3] : "0.0.0.0";
    MDC.put("context", context);
    MDC.put("hostId", System.getProperty("host.id", "UNKNOWN"));
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    final Logger logger = LoggerFactory.getLogger(RestApplication.class);
    try {
        logger.info("Java process starting");
        logger.debug(String.format("java.version:[%s] java.vendor:[%s]", System.getProperty("java.version"),
                System.getProperty("java.vendor")));
        @SuppressWarnings("resource")
        final ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        logger.debug("Finished getting ApplicationContext");
        final ApplicationLifecycleController applicationLifecycleController = applicationContext
                .getBean(ApplicationLifecycleController.class);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("Shutdown hook invoked - Commencing graceful termination of Java process");
            applicationLifecycleController.shutdownApplication();
            logger.info("Java process terminating");
        }));
        applicationLifecycleController.startApplication(servicePort, statusPort, bindAddress);
        Thread.currentThread().join();
    } catch (final InterruptedException e) {
        logger.info("Java process interrupted");
        System.exit(1);
    } catch (final Exception e) {
        logger.error("Error starting Java process", e);
        System.exit(1);
    }
}

From source file:com.machinelinking.cli.loader.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.err.println("Usage: $0 <config-file> <dump>");
        System.exit(1);//from   w  ww .  jav a  2 s  .  co  m
    }

    try {
        final File configFile = check(args[0]);
        final File dumpFile = check(args[1]);
        final Properties properties = new Properties();
        properties.load(FileUtils.openInputStream(configFile));

        final Flag[] flags = WikiPipelineFactory.getInstance().toFlags(getPropertyOrFail(properties,
                LOADER_FLAGS_PROP,
                "valid flags: " + Arrays.toString(WikiPipelineFactory.getInstance().getDefinedFlags())));
        final JSONStorageFactory jsonStorageFactory = MultiJSONStorageFactory
                .loadJSONStorageFactory(getPropertyOrFail(properties, LOADER_STORAGE_FACTORY_PROP, null));
        final String jsonStorageConfig = getPropertyOrFail(properties, LOADER_STORAGE_CONFIG_PROP, null);
        final URL prefixURL = readURL(getPropertyOrFail(properties, LOADER_PREFIX_URL_PROP,
                "expected a valid URL prefix like: http://en.wikipedia.org/"), LOADER_PREFIX_URL_PROP);

        final DefaultJSONStorageLoader[] loader = new DefaultJSONStorageLoader[1];
        final boolean[] finalReportProduced = new boolean[] { false };
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (!finalReportProduced[0] && loader[0] != null) {
                    System.err.println(
                            "Process interrupted. Partial loading report: " + loader[0].createReport());
                }
                System.err.println("Shutting down.");
            }
        }));

        final JSONStorageConfiguration storageConfig = jsonStorageFactory
                .createConfiguration(jsonStorageConfig);
        try (final JSONStorage storage = jsonStorageFactory.createStorage(storageConfig)) {
            loader[0] = new DefaultJSONStorageLoader(WikiPipelineFactory.getInstance(), flags, storage);

            final StorageLoaderReport report = loader[0].load(prefixURL,
                    FileUtil.openDecompressedInputStream(dumpFile));
            System.err.println("Loading report: " + report);
            finalReportProduced[0] = true;
        }
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:com.arpnetworking.tsdaggregator.TsdAggregator.java

/**
 * Entry point for Time Series Data (TSD) Aggregator.
 *
 * @param args the command line arguments
 *//*from  w  ww .  j av  a  2 s .  c o  m*/
public static void main(final String[] args) {
    LOGGER.info("Launching tsd-aggregator");

    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOGGER.error("Unhandled exception!", throwable);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.stop();
        }
    }));

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug(String.format("Loading configuration from file; file=%s", args[0]));

    final File configurationFile = new File(args[0]);
    final Configurator<TsdAggregator, TsdAggregatorConfiguration> configurator = new Configurator<>(
            TsdAggregator.class, TsdAggregatorConfiguration.class);
    final ObjectMapper objectMapper = TsdAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper).setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()).addListener(configurator)
            .build();

    configuration.launch();

    final AtomicBoolean isRunning = new AtomicBoolean(true);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping tsd-aggregator");
            configuration.shutdown();
            configurator.shutdown();
            isRunning.set(false);
        }
    }));

    while (isRunning.get()) {
        try {
            Thread.sleep(30000);
        } catch (final InterruptedException e) {
            break;
        }
    }

    LOGGER.info("Exiting tsd-aggregator");
}

From source file:ch.algotrader.event.TopicEventDumper.java

public static void main(String... args) throws Exception {

    SingleConnectionFactory jmsActiveMQFactory = new SingleConnectionFactory(
            new ActiveMQConnectionFactory("tcp://localhost:61616"));
    jmsActiveMQFactory.afterPropertiesSet();
    jmsActiveMQFactory.resetConnection();

    ActiveMQTopic topic = new ActiveMQTopic(">");

    DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer();
    messageListenerContainer.setDestination(topic);
    messageListenerContainer.setConnectionFactory(jmsActiveMQFactory);
    messageListenerContainer.setSubscriptionShared(false);
    messageListenerContainer.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER);

    messageListenerContainer.setMessageListener((MessageListener) message -> {
        try {/*from  w w  w.  ja  va 2s . c  o m*/
            Destination destination = message.getJMSDestination();
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println(destination + " -> " + textMessage.getText());
            } else if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);
                System.out.println(destination + " -> " + new String(bytes, Charsets.UTF_8));
            }
        } catch (JMSException ex) {
            throw new UnrecoverableCoreException(ex);
        }
    });

    messageListenerContainer.initialize();
    messageListenerContainer.start();

    System.out.println("Dumping messages from all topics");

    Runtime.getRuntime().addShutdownHook(new Thread(messageListenerContainer::stop));

    Thread.sleep(Long.MAX_VALUE);
}