Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

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

Prototype

public Thread() 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:net.semanticmetadata.lire.solr.AddImages.java

public static void main(String[] args) throws IOException, InterruptedException {
    BitSampling.readHashFunctions();//from ww w  .ja va2s . c  om
    LinkedList<Thread> threads = new LinkedList<Thread>();
    for (int j = 10; j < 21; j++) {
        final int tz = j;
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    List<File> files = FileUtils
                            .getAllImageFiles(new File("D:\\DataSets\\WIPO-US\\jpg_us_trim\\" + tz), true);
                    int count = 0;
                    BufferedWriter br = new BufferedWriter(new FileWriter("add-us-" + tz + ".xml", false));
                    br.write("<add>\n");
                    for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
                        File file = iterator.next();
                        br.write(createAddDoc(file).toString());
                        count++;
                        //                            if (count % 1000 == 0) System.out.print('.');
                    }
                    br.write("</add>\n");
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
            }
        };
        t.start();
        threads.add(t);
    }
    for (Iterator<Thread> iterator = threads.iterator(); iterator.hasNext();) {
        Thread next = iterator.next();
        next.join();
    }
}

From source file:io.amient.examples.TwitterStreamDemo.java

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

    final String bootstrapServers = args.length == 1 ? args[0] : DEFAULT_BOOTSTRAP_SERVERS;

    //1. Launch Embedded Connect Instance for ingesting twitter feed filtered on "money" into twitter topic
    ConnectEmbedded connect = createTwitterSourceConnectInstance(bootstrapServers);
    connect.start();/*from   w w w.  j  av  a2  s.c om*/

    //2. Launch Kafka Streams Topology - 
    KafkaStreams streams = createTwitterStreamsInstance(bootstrapServers);
    try {
        streams.start();
    } catch (Throwable e) {
        log.error("Stopping the application due to streams initialization error ", e);
        connect.stop();
    }

    // The Embedded Connect's shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            connect.stop();
        }
    });

    try {
        connect.awaitStop();
        log.info("Connect closed cleanly...");
    } finally {
        streams.close();
        log.info("Stream closed cleanly...");
    }
}

From source file:io.amient.examples.wikipedia.WikipediaStreamDemo.java

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

    final String bootstrapServers = args.length == 1 ? args[0] : DEFAULT_BOOTSTRAP_SERVERS;

    //1. Launch Embedded Connect Instance for ingesting Wikipedia IRC feed into wikipedia-raw topic
    ConnectEmbedded connect = createWikipediaFeedConnectInstance(bootstrapServers);
    connect.start();/*from   www .j  a  v  a  2s  . co  m*/

    //2. Launch Kafka Streams Topology
    KafkaStreams streams = createWikipediaStreamsInstance(bootstrapServers);
    try {
        streams.start();
    } catch (Throwable e) {
        log.error("Stopping the application due to streams initialization error ", e);
        connect.stop();
    }

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

    try {
        connect.awaitStop();
        log.info("Connect closed cleanly...");
    } finally {
        streams.close();
        log.info("Streams closed cleanly...");
    }
}

From source file:cn.webank.ecif.index.server.EcifIndexServer.java

/**
 * @param args//  w ww .  j a  va2s . c  o  m
 */
public static void main(String[] args) {
    final EcifIndexServer server = new EcifIndexServer();
    // start spring context;
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    context.getEnvironment().setActiveProfiles("product");
    context.setConfigLocation("application.xml");
    context.refresh();
    context.start();

    // thread pool construct
    ThreadPoolTaskExecutor taskThreadPool = context.getBean("taskExecutor", ThreadPoolTaskExecutor.class);

    server.setTaskThreadPool(taskThreadPool);

    ExecutorService fixedThreadPool = context.getBean("fixedTaskExecutor", ExecutorService.class);

    server.setSchedulerThreadPool(fixedThreadPool);

    EcifThreadFactory threadFactory = context.getBean("cn.webank.ecif.index.async.EcifThreadFactory",
            EcifThreadFactory.class);

    server.setThreadFactory(threadFactory);

    Properties props = context.getBean("ecifProperties", java.util.Properties.class);

    WeBankServiceDispatcher serviceDispatcher = context.getBean(
            "cn.webank.framework.biz.service.support.WeBankServiceDispatcher", WeBankServiceDispatcher.class);

    ReloadableResourceBundleMessageSource bundleMessageSource = context.getBean("messageSource",
            ReloadableResourceBundleMessageSource.class);

    String topics = props.getProperty("listener.topics");
    String[] splits = topics.split(",");

    SolaceManager solaceManager = context.getBean("cn.webank.framework.message.SolaceManager",
            SolaceManager.class);
    MessageListener messageLisener = new MessageListener(
            // props.getProperty("listener.queue"),
            Arrays.asList(splits), Integer.parseInt(props.getProperty("listener.scanintervalseconds", "5")),
            taskThreadPool, Integer.parseInt(props.getProperty("listener.timeoutseconds", "5")),
            serviceDispatcher, solaceManager, bundleMessageSource);
    server.addListenerOnSchedule(messageLisener);

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

            } catch (Exception e) {
                LOG.error("shutdown error", e);
            }
        }
    });

    // hold server
    try {
        LOG.info("ecif-index server start ok!");
        server.start();
    } catch (Exception e) {
        try {
            // close resource
            server.shutDown();
            if (context != null) {
                context.close();
            }

        } catch (Exception ex) {
            LOG.error("shutdown error", ex);
        }
    }

    LOG.info("ecif-index server stop !");
}

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();//from w w  w.java 2  s  .  co  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:com.netflix.suro.SuroServer.java

public static void main(String[] args) throws IOException {
    final AtomicReference<Injector> injector = new AtomicReference<Injector>();

    try {//from w  w  w  .ja  v a  2s  . c o  m
        // Parse the command line
        Options options = createOptions();
        final CommandLine line = new BasicParser().parse(options, args);

        // Load the properties file
        final Properties properties = new Properties();
        if (line.hasOption('p')) {
            properties.load(new FileInputStream(line.getOptionValue('p')));
        }

        // Bind all command line options to the properties with prefix "SuroServer."
        for (Option opt : line.getOptions()) {
            String name = opt.getOpt();
            String value = line.getOptionValue(name);
            String propName = PROP_PREFIX + opt.getArgName();
            if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) {
                properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) {
                properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) {
                properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else {
                properties.setProperty(propName, value);
            }
        }

        create(injector, properties);
        injector.get().getInstance(LifecycleManager.class).start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
                } catch (IOException e) {
                    // do nothing because Closeables.close will swallow IOException
                }
            }
        });

        waitForShutdown(getControlPort(properties));
    } catch (Throwable e) {
        System.err.println("SuroServer startup failed: " + e.getMessage());
        System.exit(-1);
    } finally {
        Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
    }
}

From source file:com.vitco.Main.java

public static void main(String[] args) throws Exception {
    // display version number on splash screen
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash != null) {
        Graphics2D g = splash.createGraphics();
        if (g != null) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            Font font = Font
                    .createFont(Font.TRUETYPE_FONT,
                            new SaveResourceLoader("resource/font/arcade.ttf").asInputStream())
                    .deriveFont(Font.PLAIN, 42f);
            g.setFont(font);// w ww .ja v  a 2s . co  m
            //g.setFont(g.getFont().deriveFont(9f));
            g.setColor(VitcoSettings.SPLASH_SCREEN_OVERLAY_TEXT_COLOR);
            int width = g.getFontMetrics().stringWidth(VitcoSettings.VERSION_ID);
            g.drawString(VitcoSettings.VERSION_ID, 400 - 20 - width, 110);
            splash.update();
            g.dispose();
        }
    }

    // the JIDE license
    SaveResourceLoader saveResourceLoader = new SaveResourceLoader("resource/jidelicense.txt");
    if (!saveResourceLoader.error) {
        String[] jidelicense = saveResourceLoader.asLines();
        if (jidelicense.length == 3) {
            com.jidesoft.utils.Lm.verifyLicense(jidelicense[0], jidelicense[1], jidelicense[2]);
        }
    }

    // check if we are in debug mode
    if ((args.length > 0) && args[0].equals("debug")) {
        ErrorHandler.setDebugMode();
        debug = true;
    }

    // build the application
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "com/vitco/glue/config.xml");

    // for debugging
    if (debug) {
        ((ActionManager) context.getBean("ActionManager")).performValidityCheck();
        ((ComplexActionManager) context.getBean("ComplexActionManager")).performValidityCheck();
    }

    // open vsd file when program is started with "open with"
    MainMenuLogic mainMenuLogic = ((MainMenuLogic) context.getBean("MainMenuLogic"));
    for (String arg : args) {
        if (arg.endsWith(".vsd")) {
            File file = new File(arg);
            if (file.exists() && !file.isDirectory()) {
                mainMenuLogic.openFile(file);
                break;
            }
        }
    }

    // perform shortcut check
    ((ShortcutManager) context.getBean("ShortcutManager")).doSanityCheck(debug);
    //        // test console
    //        final Console console = ((Console) context.getBean("Console"));
    //        new Thread() {
    //            public void run() {
    //                while (true) {
    //                    console.addLine("text");
    //                    try {
    //                        sleep(2000);
    //                    } catch (InterruptedException e) {
    //                       //e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();

    // add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // make reference so Preferences object doesn't get destroyed
            Preferences pref = ((Preferences) context.getBean("Preferences"));
            // trigger @PreDestroy
            context.close();
            // store the preferences (this needs to be done here, b/c
            // some PreDestroys are used to store preferences!)
            pref.save();
        }
    });
}

From source file:com.chigix.autosftp.Application.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("P").longOpt("port").hasArg().build())
            .addOption(Option.builder("h").longOpt("help").desc("Print this message").build())
            .addOption(Option.builder("i").argName("identity_file").hasArg().build());
    int port = 22;
    CommandLine line;//from   w  w w .  j  a v  a2 s  .c  o  m
    try {
        line = new DefaultParser().parse(options, args);
    } catch (UnrecognizedOptionException ex) {
        System.err.println(ex.getMessage());
        return;
    } catch (ParseException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("autosftp /path/to/watch [user@]host2:[file2]", options, true);
        return;
    }
    String givenPort;
    if (line.hasOption("port") && StringUtils.isNumeric(givenPort = line.getOptionValue("port"))) {
        port = Integer.valueOf(givenPort);
    }
    if (line.getArgs().length < 0) {
        System.err.println("Please provide a path to watch.");
        return;
    }
    localPath = Paths.get(line.getArgs()[0]);
    if (line.getArgs().length < 1) {
        System.err.println("Please provide remote ssh information.");
        return;
    }
    SshAddressParser addressParse;
    try {
        addressParse = new SshAddressParser().parse(line.getArgs()[1]);
    } catch (SshAddressParser.InvalidAddressException ex) {
        System.err.println(ex.getMessage());
        return;
    }
    if (addressParse.getDefaultDirectory() != null) {
        remotePath = Paths.get(addressParse.getDefaultDirectory());
    }
    try {
        sshSession = new JSch().getSession(addressParse.getUsername(), addressParse.getHost(), port);
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    try {
        sshOpen();
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        sshClose();
    }
    System.out.println("Remote Default Path: " + remotePath);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            sshClose();
            System.out.println("Bye~~~");
        }

    });
    try {
        watchDir(Paths.get(line.getArgs()[0]));
    } catch (Exception ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:javarestart.JavaRestartLauncher.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <URL> {<MainClass>}");
        return;/*from  w  ww  .j a  v a 2 s .  co m*/
    }

    if (args[0].equals("fork")) {
        String[] args2 = new String[args.length - 1];
        for (int i = 0; i < args.length - 1; i++) {
            args2[i] = args[i + 1];
        }
        fork(args2);
        return;
    }

    AppClassloader loader = new AppClassloader(args[0]);
    Thread.currentThread().setContextClassLoader(loader);
    String main;
    JSONObject obj = getJSON(args[0]);
    if (args.length < 2) {
        main = (String) obj.get("main");
    } else {
        main = args[1];
    }

    String splash = (String) obj.get("splash");
    if (splash != null) {
        SplashScreen scr = SplashScreen.getSplashScreen();
        if (scr != null) {
            URL url = loader.getResource(splash);
            scr.setImageURL(url);
        }
    }

    //auto close splash after 45 seconds
    Thread splashClose = new Thread() {
        @Override
        public void run() {
            try {
                sleep(45000);
            } catch (InterruptedException e) {
            }
            SplashScreen scr = SplashScreen.getSplashScreen();
            if ((scr != null) && (scr.isVisible())) {
                scr.close();
            }
        }
    };
    splashClose.setDaemon(true);
    splashClose.start();

    Class mainClass = loader.loadClass(main);
    Method mainMethod = mainClass.getMethod("main", String[].class);
    mainMethod.setAccessible(true);
    mainMethod.invoke(null, new Object[] { new String[0] });
}

From source file:com.sina.dip.twill.HelloWorldClassDependent.java

public static void main(String[] args) {
    String zkStr = "localhost:2181";

    YarnConfiguration yarnConfiguration = new YarnConfiguration();

    final TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfiguration, zkStr);

    twillRunner.start();/*from  www  .j a  v  a2s  .c o  m*/

    String yarnClasspath = yarnConfiguration.get(YarnConfiguration.YARN_APPLICATION_CLASSPATH,
            "/usr/lib/hadoop/*,/usr/lib/hadoop-0.20-mapreduce/*,/usr/lib/hadoop-hdfs/*,/usr/lib/hadoop-mapreduce/*,/usr/lib/hadoop-yarn/*");

    List<String> applicationClassPaths = Lists.newArrayList();

    Iterables.addAll(applicationClassPaths, Splitter.on(",").split(yarnClasspath));

    final TwillController controller = twillRunner.prepare(new HelloWorldApplication())
            .withApplicationClassPaths(applicationClassPaths)
            .withBundlerClassAcceptor(new HadoopClassExcluder()).start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                Futures.getUnchecked(controller.terminate());
            } finally {
                twillRunner.stop();
            }
        }
    });

    try {
        controller.awaitTerminated();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}