Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

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

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:CurrentThreadDemo.java

public static void main(String args[]) {
    Thread t = Thread.currentThread();

    System.out.println("Current thread: " + t);

    t.setName("My Thread");
    System.out.println("After name change: " + t);

    try {//from  ww  w.java 2  s.  c  o m
        for (int n = 5; n > 0; n--) {
            System.out.println(n);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        System.out.println("Main thread interrupted");
    }
}

From source file:info.bitoo.Main.java

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

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

    URL torrentURL = null;

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

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

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

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

}

From source file: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   w  w  w.  j a va2 s . c om*/

    // 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:mosaicsimulation.MosaicLockstepServer.java

public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption("s", "serverPort", true, "Listening TCP port used to initiate handshakes");
    opts.addOption("n", "nClients", true, "Number of clients that will participate in the session");
    opts.addOption("t", "tickrate", true, "Number of transmission session to execute per second");
    opts.addOption("m", "maxUDPPayloadLength", true, "Max number of bytes per UDP packet");
    opts.addOption("c", "connectionTimeout", true, "Timeout for UDP connections");

    DefaultParser parser = new DefaultParser();
    CommandLine commandLine = null;/*from  w  w w .  j a va2  s .  co  m*/
    try {
        commandLine = parser.parse(opts, args);
    } catch (ParseException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    int serverPort = Integer.parseInt(commandLine.getOptionValue("serverPort"));
    int nClients = Integer.parseInt(commandLine.getOptionValue("nClients"));
    int tickrate = Integer.parseInt(commandLine.getOptionValue("tickrate"));
    int maxUDPPayloadLength = Integer.parseInt(commandLine.getOptionValue("maxUDPPayloadLength"));
    int connectionTimeout = Integer.parseInt(commandLine.getOptionValue("connectionTimeout"));

    Thread serverThread = LockstepServer.builder().clientsNumber(nClients).tcpPort(serverPort)
            .tickrate(tickrate).maxUDPPayloadLength(maxUDPPayloadLength).connectionTimeout(connectionTimeout)
            .build();

    serverThread.setName("Main-server-thread");
    serverThread.start();

    try {
        serverThread.join();
    } catch (InterruptedException ex) {
        LOG.error("Server interrupted while joining");
    }
}

From source file:com.framework.infrastructure.utils.ReflectionUtils.java

public static void main(String args[]) {
    Worker worker = new Worker();
    Thread thread = new Thread();
    thread.setName("nihao");
    worker.setTask(thread);//from  w w  w.  j a v a2s  .co m

    Thread thread2 = (Thread) ReflectionUtils.getFieldValue(worker, "firstTask");
    System.out.println(thread2.getName());

}

From source file:com.btoddb.fastpersitentqueue.speedtest.SpeedTest.java

public static void main(String[] args) throws Exception {
    if (0 == args.length) {
        System.out.println();// w w w  . j  a  v a2 s  . c o  m
        System.out.println("ERROR: must specify the config file path/name");
        System.out.println();
        System.exit(1);
    }

    SpeedTestConfig config = SpeedTestConfig.create(args[0]);

    System.out.println(config.toString());

    File theDir = new File(config.getDirectory(), "speed-" + UUID.randomUUID().toString());
    FileUtils.forceMkdir(theDir);

    Fpq queue = config.getFpq();
    queue.setJournalDirectory(new File(theDir, "journals"));
    queue.setPagingDirectory(new File(theDir, "pages"));

    try {
        queue.init();

        //
        // start workers
        //

        AtomicLong counter = new AtomicLong();
        AtomicLong pushSum = new AtomicLong();
        AtomicLong popSum = new AtomicLong();

        long startTime = System.currentTimeMillis();

        Set<SpeedPushWorker> pushWorkers = new HashSet<SpeedPushWorker>();
        for (int i = 0; i < config.getNumberOfPushers(); i++) {
            pushWorkers.add(new SpeedPushWorker(queue, config, counter, pushSum));
        }

        Set<SpeedPopWorker> popWorkers = new HashSet<SpeedPopWorker>();
        for (int i = 0; i < config.getNumberOfPoppers(); i++) {
            popWorkers.add(new SpeedPopWorker(queue, config, popSum));
        }

        ExecutorService pusherExecSrvc = Executors.newFixedThreadPool(
                config.getNumberOfPushers() + config.getNumberOfPoppers(), new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable runnable) {
                        Thread t = new Thread(runnable);
                        t.setName("SpeedTest-Pusher");
                        return t;
                    }
                });

        ExecutorService popperExecSrvc = Executors.newFixedThreadPool(
                config.getNumberOfPushers() + config.getNumberOfPoppers(), new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable runnable) {
                        Thread t = new Thread(runnable);
                        t.setName("SpeedTest-Popper");
                        return t;
                    }
                });

        long startPushing = System.currentTimeMillis();
        for (SpeedPushWorker sw : pushWorkers) {
            pusherExecSrvc.submit(sw);
        }

        long startPopping = System.currentTimeMillis();
        for (SpeedPopWorker sw : popWorkers) {
            popperExecSrvc.submit(sw);
        }

        //
        // wait to finish
        //

        long endTime = startTime + config.getDurationOfTest() * 1000;
        long endPushing = 0;
        long displayTimer = 0;
        while (0 == endPushing || !queue.isEmpty()) {
            // display status every second
            if (1000 < (System.currentTimeMillis() - displayTimer)) {
                System.out.println(String.format("status (%ds) : journals = %d : memory segments = %d",
                        (endTime - System.currentTimeMillis()) / 1000,
                        queue.getJournalMgr().getJournalIdMap().size(),
                        queue.getMemoryMgr().getSegments().size()));
                displayTimer = System.currentTimeMillis();
            }

            pusherExecSrvc.shutdown();
            if (pusherExecSrvc.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                endPushing = System.currentTimeMillis();
                // tell poppers, all pushers are finished
                for (SpeedPopWorker sw : popWorkers) {
                    sw.stopWhenQueueEmpty();
                }
            }
        }

        long endPopping = System.currentTimeMillis();

        popperExecSrvc.shutdown();
        popperExecSrvc.awaitTermination(10, TimeUnit.SECONDS);

        long numberOfPushes = 0;
        for (SpeedPushWorker sw : pushWorkers) {
            numberOfPushes += sw.getNumberOfEntries();
        }

        long numberOfPops = 0;
        for (SpeedPopWorker sw : popWorkers) {
            numberOfPops += sw.getNumberOfEntries();
        }

        long pushDuration = endPushing - startPushing;
        long popDuration = endPopping - startPopping;

        System.out.println("push - pop checksum = " + pushSum.get() + " - " + popSum.get() + " = "
                + (pushSum.get() - popSum.get()));
        System.out.println("push duration = " + pushDuration);
        System.out.println("pop duration = " + popDuration);
        System.out.println();
        System.out.println("pushed = " + numberOfPushes);
        System.out.println("popped = " + numberOfPops);
        System.out.println();
        System.out.println("push entries/sec = " + numberOfPushes / (pushDuration / 1000f));
        System.out.println("pop entries/sec = " + numberOfPops / (popDuration / 1000f));
        System.out.println();
        System.out.println("journals created = " + queue.getJournalsCreated());
        System.out.println("journals removed = " + queue.getJournalsRemoved());
    } finally {
        if (null != queue) {
            queue.shutdown();
        }
        //            FileUtils.deleteDirectory(theDir);
    }
}

From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java

public static void main(String[] args) {
    try {/*from   w  w  w.jav  a 2 s  .  com*/
        if (!Constants.DATA_DIR.exists() && !Constants.DATA_DIR.mkdirs())
            throw new RuntimeException("Could not create data directory");
        if (!Constants.ADDONS_DIR.exists() && !Constants.ADDONS_DIR.mkdirs())
            throw new RuntimeException("Could not create addons directory");
        if (!Constants.SETTINGS_FILE.exists() && !Constants.SETTINGS_FILE.createNewFile())
            throw new RuntimeException("Could not create settings file");
        if (Constants.DATA_DIR.isFile())
            throw new RuntimeException("Data directory is file");
        if (Constants.ADDONS_DIR.isFile())
            throw new RuntimeException("Addons directory is file");
        if (Constants.SETTINGS_FILE.isDirectory())
            throw new RuntimeException("Settings file is directory");

        try {
            Class<?> clazz = Class.forName("org.eclipse.swt.widgets.Event");
            Object location = clazz.getProtectionDomain() != null
                    && clazz.getProtectionDomain().getCodeSource() != null
                            ? clazz.getProtectionDomain().getCodeSource().getLocation()
                            : "";
            throw new RuntimeException("SWT should not be loaded. Instead, it was loaded from " + location);
        } catch (ClassNotFoundException ignored) {
            loadSWTLibrary();
        }

        DisplayPumper displayPumper = new DisplayPumper();

        if (System.getProperty("os.name").toLowerCase().contains("mac")) {
            System.out.println("Attemting to force main thread");
            Executor executor;
            try {
                Class<?> dispatchClass = Class.forName("com.apple.concurrent.Dispatch");
                Object dispatchInstance = dispatchClass.getMethod("getInstance").invoke(null);
                executor = (Executor) dispatchClass.getMethod("getNonBlockingMainQueueExecutor")
                        .invoke(dispatchInstance);
            } catch (Throwable throwable) {
                throw new RuntimeException("Could not reflectively access Dispatch", throwable);
            }
            if (executor != null) {
                executor.execute(displayPumper);
            } else {
                throw new RuntimeException("Could not load executor");
            }
        } else {
            Thread pumpThread = new Thread(displayPumper);
            pumpThread.setName("Display Pumper");
            pumpThread.start();
        }
        while (!displayPumper.isReady())
            ;

        Display display = displayPumper.getDisplay();
        Shell shell = displayPumper.getShell();
        Splash splashScreen = new Splash(display);
        splashScreen.updateState(BootSequence.CHECKING_LIBRARIES);
        checkPackagedLibrary(splashScreen, "enjarify", Constants.ENJARIFY_VERSION,
                BootSequence.CHECKING_ENJARIFY, BootSequence.CLEANING_ENJARIFY, BootSequence.MOVING_ENJARIFY);
        checkPackagedLibrary(splashScreen, "Krakatau", Constants.KRAKATAU_VERSION,
                BootSequence.CHECKING_KRAKATAU, BootSequence.CLEANING_KRAKATAU, BootSequence.MOVING_KRAKATAU);

        try {
            if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }
        } catch (Exception exception) { //Not important. No point notifying the user
        }

        Helios.main(args, shell, splashScreen);
        synchronized (displayPumper.getSynchronizer()) {
            displayPumper.getSynchronizer().wait();
        }
        System.exit(0);
    } catch (Throwable t) {
        displayError(t);
        System.exit(1);
    }
}

From source file:Test.java

public static void main(String[] args) {
    final AtomicLong orderIdGenerator = new AtomicLong(0);
    final List<Item> orders = Collections.synchronizedList(new ArrayList<Item>());

    for (int i = 0; i < 10; i++) {
        Thread orderCreationThread = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    long orderId = orderIdGenerator.incrementAndGet();
                    Item order = new Item(Thread.currentThread().getName(), orderId);
                    orders.add(order);/* www.j av  a2 s .co  m*/
                }
            }
        });
        orderCreationThread.setName("Order Creation Thread " + i);
        orderCreationThread.start();
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Set<Long> orderIds = new HashSet<Long>();
    for (Item order : orders) {
        orderIds.add(order.getID());
        System.out.println("Order id:" + order.getID());
    }
}

From source file:io.seldon.importer.articles.FileItemAttributesImporter.java

/**
 * @param args//from   w w  w . ja va 2s  .c o  m
 * @throws InterruptedException 
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws InterruptedException, FileNotFoundException {

    FailFast failFast = new FailFast(Thread.currentThread());
    { // Fail Fast thread
        Thread fail_fast_thread = new Thread(failFast);
        fail_fast_thread.setName("fail_fast_thread");
        fail_fast_thread.start();
    }

    try {
        Args.parse(FileItemAttributesImporter.class, args);

        DefaultApiClient client = new DefaultApiClient(apiUrl, consumerKey, consumerSecret, API_TIMEOUT);

        FileItemAttributesImporter fixer = new FileItemAttributesImporter(client);

        fixer.setFailFast(failFast);
        fixer.run();

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        Args.usage(FileItemAttributesImporter.class);
    }
}

From source file:io.seldon.importer.articles.ItemAttributesImporter.java

/**
 * @param args/*  w  w  w .  j av a  2  s. co m*/
 * @throws InterruptedException 
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws InterruptedException, FileNotFoundException {

    FailFast failFast = new FailFast(Thread.currentThread());
    { // Fail Fast thread
        Thread fail_fast_thread = new Thread(failFast);
        fail_fast_thread.setName("fail_fast_thread");
        fail_fast_thread.start();
    }

    try {
        Args.parse(ItemAttributesImporter.class, args);
        { // Determine opMode by checking for urlFile
            if (urlFile != null) {
                opMode = OperationMode.OPERATION_MODE_FILE_IMPORTER;
            }
        }

        DefaultApiClient client = new DefaultApiClient(apiUrl, consumerKey, consumerSecret, API_TIMEOUT);

        ItemAttributesImporter fixer = new ItemAttributesImporter(client);

        fixer.setFailFast(failFast);
        fixer.run();

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        Args.usage(ItemAttributesImporter.class);
    }
}