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.twitter.heron.healthmgr.HealthManager.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options slaManagerCliOptions = constructCliOptions();

    // parse the help options first.
    Options helpOptions = constructHelpOptions();
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption("h")) {
        usage(slaManagerCliOptions);//w w  w.  j  ava  2s  .c  o m
        return;
    }

    try {
        cmd = parser.parse(slaManagerCliOptions, args);
    } catch (ParseException e) {
        usage(slaManagerCliOptions);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    HealthManagerMode mode = HealthManagerMode.cluster;
    if (hasOption(cmd, CliArgs.MODE)) {
        mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE));
    }

    Config config;
    switch (mode) {
    case cluster:
        config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig())
                .putAll(commandLineConfigs(cmd)).build());
        break;

    case local:
        if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) {
            throw new IllegalArgumentException("Missing heron_home or config_path argument");
        }
        String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME);
        String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH);
        config = Config.toLocalMode(
                Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null))
                        .putAll(commandLineConfigs(cmd)).build());
        break;

    default:
        throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE));
    }

    setupLogging(cmd, config);

    LOG.info("Static Heron config loaded successfully ");
    LOG.fine(config.toString());

    // load the default config value and override with any command line values
    String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key());
    metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName);

    String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key());
    metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl);

    AbstractModule module = buildMetricsProviderModule(metricsUrl, metricSourceClassName);
    HealthManager healthManager = new HealthManager(config, module);

    LOG.info("Initializing health manager");
    healthManager.initialize();

    LOG.info("Starting Health Manager metirc posting thread");
    HealthManagerMetrics publishingMetricsRunnable = null;
    if (hasOption(cmd, CliArgs.METRICSMGR_PORT)) {
        publishingMetricsRunnable = new HealthManagerMetrics(
                Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT)));
    }

    LOG.info("Starting Health Manager");
    PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies);
    ScheduledFuture<?> future = policyExecutor.start();
    if (publishingMetricsRunnable != null) {
        new Thread(publishingMetricsRunnable).start();
    }
    try {
        future.get();
    } finally {
        policyExecutor.destroy();
        if (publishingMetricsRunnable != null) {
            publishingMetricsRunnable.close();
        }
    }
}

From source file:examples.KafkaStreamsDemo.java

public static void main(String[] args) throws InterruptedException, SQLException {
    /**//  w w w  .  j a  v a 2s.  c o  m
     * The example assumes the following SQL schema
     *
     *    DROP DATABASE IF EXISTS beer_sample_sql;
     *    CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci;
     *    USE beer_sample_sql;
     *
     *    CREATE TABLE breweries (
     *       id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       description TEXT,
     *       country VARCHAR(256),
     *       city VARCHAR(256),
     *       state VARCHAR(256),
     *       phone VARCHAR(40),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     *
     *
     *    CREATE TABLE beers (
     *       id VARCHAR(256) NOT NULL,
     *       brewery_id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       category VARCHAR(256),
     *       style VARCHAR(256),
     *       description TEXT,
     *       abv DECIMAL(10,2),
     *       ibu DECIMAL(10,2),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     */
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.err.println("Failed to load MySQL JDBC driver");
    }
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root",
            "secret");
    final PreparedStatement insertBrewery = connection.prepareStatement(
            "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " name=VALUES(name), description=VALUES(description), country=VALUES(country),"
                    + " country=VALUES(country), city=VALUES(city), state=VALUES(state),"
                    + " phone=VALUES(phone), updated_at=VALUES(updated_at)");
    final PreparedStatement insertBeer = connection.prepareStatement(
            "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description),"
                    + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv),"
                    + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)");

    String schemaRegistryUrl = "http://localhost:8081";

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class);

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    KStreamBuilder builder = new KStreamBuilder();

    KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample");

    KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() {
        @Override
        public JsonNode apply(GenericRecord value) {
            ByteBuffer buf = (ByteBuffer) value.get("content");
            try {
                JsonNode doc = MAPPER.readTree(buf.array());
                return doc;
            } catch (IOException e) {
                return null;
            }
        }
    }).branch(new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name")
                    && value.has("description") && value.has("category") && value.has("style")
                    && value.has("abv") && value.has("ibu") && value.has("updated");
        }
    }, new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description")
                    && value.has("country") && value.has("city") && value.has("state") && value.has("phone")
                    && value.has("updated");
        }
    });
    documents[0].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBeer.setString(1, key);
                insertBeer.setString(2, value.get("brewery_id").asText());
                insertBeer.setString(3, value.get("name").asText());
                insertBeer.setString(4, value.get("description").asText());
                insertBeer.setString(5, value.get("category").asText());
                insertBeer.setString(6, value.get("style").asText());
                insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText()));
                insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText()));
                insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBeer.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });
    documents[1].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBrewery.setString(1, key);
                insertBrewery.setString(2, value.get("name").asText());
                insertBrewery.setString(3, value.get("description").asText());
                insertBrewery.setString(4, value.get("country").asText());
                insertBrewery.setString(5, value.get("city").asText());
                insertBrewery.setString(6, value.get("state").asText());
                insertBrewery.setString(7, value.get("phone").asText());
                insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBrewery.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });

    final KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            streams.close();
        }
    }));
}

From source file:com.thimbleware.jmemcached.Main.java

public static void main(String[] args) throws Exception {
    // look for external log4j.properties

    // setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "print this help screen");
    options.addOption("bl", "block-store", false, "use external (from JVM) heap");
    options.addOption("f", "mapped-file", false, "use external (from JVM) heap through a memory mapped file");
    options.addOption("bs", "block-size", true,
            "block size (in bytes) for external memory mapped file allocator.  default is 8 bytes");
    options.addOption("i", "idle", true, "disconnect after idle <x> seconds");
    options.addOption("p", "port", true, "port to listen on");
    options.addOption("m", "memory", true,
            "max memory to use; in bytes, specify K, kb, M, GB for larger units");
    options.addOption("c", "ceiling", true,
            "ceiling memory to use; in bytes, specify K, kb, M, GB for larger units");
    options.addOption("l", "listen", true, "Address to listen on");
    options.addOption("s", "size", true, "max items");
    options.addOption("b", "binary", false, "binary protocol mode");
    options.addOption("V", false, "Show version number");
    options.addOption("v", false, "verbose (show commands)");

    // read command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args);

    if (cmdline.hasOption("help") || cmdline.hasOption("h")) {
        System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion);
        System.out.println("http://thimbleware.com/projects/memcached\n");

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar memcached.jar", options);
        return;/*  ww w  . jav a 2  s.co  m*/
    }

    if (cmdline.hasOption("V")) {
        System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion);
        return;
    }

    int port = 11211;
    if (cmdline.hasOption("p")) {
        port = Integer.parseInt(cmdline.getOptionValue("p"));
    } else if (cmdline.hasOption("port")) {
        port = Integer.parseInt(cmdline.getOptionValue("port"));
    }

    InetSocketAddress addr = new InetSocketAddress(port);
    if (cmdline.hasOption("l")) {
        addr = new InetSocketAddress(cmdline.getOptionValue("l"), port);
    } else if (cmdline.hasOption("listen")) {
        addr = new InetSocketAddress(cmdline.getOptionValue("listen"), port);
    }

    int max_size = 1000000;
    if (cmdline.hasOption("s"))
        max_size = (int) Bytes.valueOf(cmdline.getOptionValue("s")).bytes();
    else if (cmdline.hasOption("size"))
        max_size = (int) Bytes.valueOf(cmdline.getOptionValue("size")).bytes();

    System.out.println("Setting max cache elements to " + String.valueOf(max_size));

    int idle = -1;
    if (cmdline.hasOption("i")) {
        idle = Integer.parseInt(cmdline.getOptionValue("i"));
    } else if (cmdline.hasOption("idle")) {
        idle = Integer.parseInt(cmdline.getOptionValue("idle"));
    }

    boolean memoryMapped = false;
    if (cmdline.hasOption("f")) {
        memoryMapped = true;
    } else if (cmdline.hasOption("mapped-file")) {
        memoryMapped = true;
    }

    boolean blockStore = false;
    if (cmdline.hasOption("bl")) {
        blockStore = true;
    } else if (cmdline.hasOption("block-store")) {
        blockStore = true;
    }

    boolean verbose = false;
    if (cmdline.hasOption("v")) {
        verbose = true;
    }

    long ceiling;
    if (cmdline.hasOption("c")) {
        ceiling = Bytes.valueOf(cmdline.getOptionValue("c")).bytes();
        System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M");
    } else if (cmdline.hasOption("ceiling")) {
        ceiling = Bytes.valueOf(cmdline.getOptionValue("ceiling")).bytes();
        System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M");
    } else if (!memoryMapped) {
        ceiling = 1024000;
        System.out.println(
                "Setting ceiling memory size to default limit of " + Bytes.bytes(ceiling).megabytes() + "M");
    } else {
        System.out
                .println("ERROR : ceiling memory size mandatory when external memory mapped file is specified");

        return;
    }

    boolean binary = false;
    if (cmdline.hasOption("b")) {
        binary = true;
    }

    int blockSize = 8;
    if (!memoryMapped && (cmdline.hasOption("bs") || cmdline.hasOption("block-size"))) {
        System.out.println(
                "WARN : block size option is only valid for memory mapped external heap storage; ignoring");
    } else if (cmdline.hasOption("bs")) {
        blockSize = Integer.parseInt(cmdline.getOptionValue("bs"));
    } else if (cmdline.hasOption("block-size")) {
        blockSize = Integer.parseInt(cmdline.getOptionValue("block-size"));
    }

    long maxBytes;
    if (cmdline.hasOption("m")) {
        maxBytes = Bytes.valueOf(cmdline.getOptionValue("m")).bytes();
        System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB");
    } else if (cmdline.hasOption("memory")) {
        maxBytes = Bytes.valueOf(cmdline.getOptionValue("memory")).bytes();
        System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB");
    } else if (!memoryMapped) {
        maxBytes = Runtime.getRuntime().maxMemory();
        System.out
                .println("Setting max memory size to JVM limit of " + Bytes.bytes(maxBytes).gigabytes() + "GB");
    } else {
        System.out.println(
                "ERROR : max memory size and ceiling size are mandatory when external memory mapped file is specified");
        return;
    }

    if (!memoryMapped && !blockStore && maxBytes > Runtime.getRuntime().maxMemory()) {
        System.out.println("ERROR : JVM heap size is not big enough. use '-Xmx"
                + String.valueOf(maxBytes / 1024000) + "m' java argument before the '-jar' option.");
        return;
    } else if ((memoryMapped || !blockStore) && maxBytes > Integer.MAX_VALUE) {
        System.out.println(
                "ERROR : when external memory mapped, memory size may not exceed the size of Integer.MAX_VALUE ("
                        + Bytes.bytes(Integer.MAX_VALUE).gigabytes() + "GB");
        return;
    }

    // create daemon and start it
    final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>();

    CacheStorage<Key, LocalCacheElement> storage;
    if (blockStore) {
        BlockStoreFactory blockStoreFactory = ByteBufferBlockStore.getFactory();

        storage = new BlockStorageCacheStorage(8, (int) ceiling, blockSize, maxBytes, max_size,
                blockStoreFactory);
    } else if (memoryMapped) {
        BlockStoreFactory blockStoreFactory = MemoryMappedBlockStore.getFactory();

        storage = new BlockStorageCacheStorage(8, (int) ceiling, blockSize, maxBytes, max_size,
                blockStoreFactory);
    } else {
        storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, max_size,
                maxBytes);
    }

    daemon.setCache(new CacheImpl(storage));
    daemon.setBinary(binary);
    daemon.setAddr(addr);
    daemon.setIdleTime(idle);
    daemon.setVerbose(verbose);
    daemon.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            if (daemon.isRunning())
                daemon.stop();
        }
    }));
}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/* www  .ja  va 2  s .  c o m*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:com.att.aro.ui.view.MainFrame.java

/**
 * Launch the application./*from www  .  java2 s  .c o m*/
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                window = new MainFrame();
                window.frmApplicationResourceOptimizer.setVisible(true);
                setLocationMap();
            } catch (Exception e) {
                e.printStackTrace();
            }
            final SplashScreen splash = new SplashScreen();
            splash.setVisible(true);
            splash.setAlwaysOnTop(true);
            new SwingWorker<Object, Object>() {
                @Override
                protected Object doInBackground() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                    }
                    return null;
                }

                @Override
                protected void done() {
                    splash.dispose();
                }
            }.execute();

            new Thread(() -> {
                if (window.ffmpegConfirmationImpl.checkFFmpegExistance() == false) {
                    SwingUtilities.invokeLater(() -> window.launchDialog(new FFmpegConfirmationDialog()));
                }
            }).start();

            new Thread(() -> {
                if (Util.isMacOS() && !window.pcapConfirmationImpl.checkPcapVersion()) {
                    SwingUtilities.invokeLater(() -> window.launchDialog(new PcapConfirmationDialog()));
                }
            }).start();
        }
    });
}

From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java

/**
 * Launch the application./*  w  ww  .ja v  a2  s.  c o m*/
 * 
 * @param args
 */
public static void main(String[] args) {
    StartSplashWindow splashWin = null;
    Thread tr = null;
    //
    // Kommandozeilenargumente parsen
    //
    try {
        if (!parseCliOptions(args)) {
            System.err.println("Error while scanning CLI-Args....");
            System.exit(-1);
        }
    } catch (Exception ex2) {
        System.err.println("Error while scanning CLI-Args....");
        System.err.println(ex2.getLocalizedMessage());
        System.exit(-1);
    }
    //
    // So, hier knnte ich splashen, alle "gefhrlichen" Sachen sind erledigt
    //
    splashWin = new StartSplashWindow();
    tr = new Thread(splashWin);
    tr.start();
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex1) {
    }
    //
    // GUI starten
    //
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getLookAndFeel());
                // Set cross-platform Java L&F (also called "Metal")
                UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            } catch (UnsupportedLookAndFeelException ex) {
                System.out.print("fallback to standart look an feel..");
            } catch (ClassNotFoundException ex) {
                System.out.print("fallback to standart look an feel..");
            } catch (InstantiationException ex) {
                System.out.print("fallback to standart look an feel..");
            } catch (IllegalAccessException ex) {
                System.out.print("fallback to standart look an feel..");
            }
            try {
                //
                // das Mainobjekt erzeugen
                //
                MainCommGUI window = new MainCommGUI();
                window.frmMainWindow.setVisible(true);
            } catch (Exception e) {
                System.err.println("Exception: " + e.getLocalizedMessage() + "\n");
                e.printStackTrace();
            }
        }
    });
    splashWin.terminate();
}

From source file:edu.berkeley.sparrow.examples.BBackend.java

public static void main(String[] args) throws IOException, TException {
    ipAddress = InetAddress.getLocalHost().toString();
    OptionParser parser = new OptionParser();
    parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
    parser.accepts("help", "print help statement");
    OptionSet options = parser.parse(args);

    if (options.has("help")) {
        parser.printHelpOn(System.out);
        System.exit(-1);//w w  w  .j ava2 s .co m
    }

    // Logger configuration: log to the console
    BasicConfigurator.configure();

    Configuration conf = new PropertiesConfiguration();

    if (options.has("c")) {
        String configFile = (String) options.valueOf("c");
        try {
            conf = new PropertiesConfiguration(configFile);
        } catch (ConfigurationException e) {
        }
    }
    // Start backend server
    LOG.setLevel(Level.toLevel(conf.getString(LOG_LEVEL, DEFAULT_LOG_LEVEL)));
    LOG.debug("debug logging on");
    int listenPort = conf.getInt(LISTEN_PORT, DEFAULT_LISTEN_PORT);
    int nodeMonitorPort = conf.getInt(NODE_MONITOR_PORT, NodeMonitorThrift.DEFAULT_NM_THRIFT_PORT);
    batchingDelay = conf.getLong(BATCHING_DELAY, DEFAULT_BATCHING_DELAY);
    String nodeMonitorHost = conf.getString(NODE_MONITOR_HOST, DEFAULT_NODE_MONITOR_HOST);
    int workerThread = conf.getInt(WORKER_THREADS, DEFAULT_WORKER_THREADS);
    appClientAdress = InetAddress.getByName(conf.getString(APP_CLIENT_IP));
    appClientPortNumber = conf.getInt(APP_CLIENT_PORT_NUMBER, DEFAULT_APP_CLIENT_PORT_NUMBER);
    executor = Executors.newFixedThreadPool(workerThread);
    // Starting logging of results
    resultLog = new SynchronizedWrite("ResultsBackend.txt");
    Thread resultLogTh = new Thread(resultLog);
    resultLogTh.start();

    BBackend protoBackend = new BBackend();
    BackendService.Processor<BackendService.Iface> processor = new BackendService.Processor<BackendService.Iface>(
            protoBackend);

    TServers.launchSingleThreadThriftServer(listenPort, processor);
    protoBackend.initialize(listenPort, nodeMonitorHost, nodeMonitorPort);

}

From source file:Main.java

public static void runThreadUseLambda() {
    new Thread(() -> System.out.println("")).start();
}

From source file:Main.java

public static void executeInThread(Runnable runnable) {
    new Thread(runnable).start();
}

From source file:Main.java

public static void runOnNewThread(Runnable runnable) {
    new Thread(runnable).start();
}