Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

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

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:ThreadDemo.java

public static void main(String args[]) {
    Thread t = new Thread(new ThreadDemo());
    System.out.println("Executing " + t.getName());
    // this will call run() fucntion
    t.start();//from ww w  . j  a v a2 s . c  om

    // interrupt the threads
    if (!t.interrupted()) {
        t.interrupt();
    }
    // block until other threads finish
    try {
        t.join();
    } catch (InterruptedException e) {
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Runner t = new Runner();
    Thread t1 = new Thread(t);
    for (int i = 0; i < 50; i++) {
        t.queue.add(i);//from  www .  ja va 2 s.co  m
    }
    System.out.println(("Number of items in queue: " + t.queue.size()));
    t1.start();
    Thread.sleep(1000);
    t1.interrupt();
    t1.join();
    System.out.println(("Number of items in queue: " + t.queue.size()));
    System.out.println(("Joined t1. Finished"));
}

From source file:GeneralInterrupt.java

public static void main(String[] args) {
    GeneralInterrupt si = new GeneralInterrupt();
    Thread t = new Thread(si);
    t.start();/* w  ww  .ja v a  2  s.com*/

    try {
        Thread.sleep(2000);
    } catch (InterruptedException x) {
    }

    System.out.println("in main() - interrupting other thread");
    t.interrupt();
    System.out.println("in main() - leaving");
}

From source file:org.apache.helix.lockmanager.LockManagerDemo.java

/**
 * LockManagerDemo clusterName, numInstances, lockGroupName, numLocks
 * @param args//from  w  w w .  j  av a2  s. c  o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    final String zkAddress = "localhost:2199";
    final String clusterName = "lock-manager-demo";
    final String lockGroupName = "lock-group";
    final int numInstances = 3;
    final int numPartitions = 12;
    final boolean startController = false;
    HelixManager controllerManager = null;
    Thread[] processArray;
    processArray = new Thread[numInstances];
    try {
        startLocalZookeeper(2199);
        HelixAdmin admin = new ZKHelixAdmin(zkAddress);
        admin.addCluster(clusterName, true);
        admin.addStateModelDef(clusterName, "OnlineOffline",
                new StateModelDefinition(StateModelConfigGenerator.generateConfigForOnlineOffline()));
        admin.addResource(clusterName, lockGroupName, numPartitions, "OnlineOffline",
                RebalanceMode.FULL_AUTO.toString());
        admin.rebalance(clusterName, lockGroupName, 1);
        for (int i = 0; i < numInstances; i++) {
            final String instanceName = "localhost_" + (12000 + i);
            processArray[i] = new Thread(new Runnable() {

                @Override
                public void run() {
                    LockProcess lockProcess = null;

                    try {
                        lockProcess = new LockProcess(clusterName, zkAddress, instanceName, startController);
                        lockProcess.start();
                        Thread.currentThread().join();
                    } catch (InterruptedException e) {
                        System.out.println(instanceName + "Interrupted");
                        if (lockProcess != null) {
                            lockProcess.stop();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
            processArray[i].start();
        }
        Thread.sleep(3000);
        controllerManager = HelixControllerMain.startHelixController(zkAddress, clusterName, "controller",
                HelixControllerMain.STANDALONE);
        Thread.sleep(5000);
        printStatus(admin, clusterName, lockGroupName);
        System.out.println("Stopping localhost_12000");
        processArray[0].interrupt();
        Thread.sleep(3000);
        printStatus(admin, clusterName, lockGroupName);
        Thread.currentThread().join();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (controllerManager != null) {
            controllerManager.disconnect();
        }
        for (Thread process : processArray) {
            if (process != null) {
                process.interrupt();
            }
        }
    }
}

From source file:InterruptibleSyncBlock.java

public static void main(String[] args) {
    try {/* w  w  w  .j a v a  2  s.  co  m*/
        InterruptibleSyncBlock sb = new InterruptibleSyncBlock();

        Thread t1 = launch(sb, "T1");
        Thread.sleep(500);

        Thread t2 = launch(sb, "T2");
        Thread t3 = launch(sb, "T3");

        Thread.sleep(1000);

        print("about to interrupt T2");
        t2.interrupt();
        print("just interrupted T2");

    } catch (InterruptedException x) {
        x.printStackTrace();
    }
}

From source file:TryThread.java

public static void main(String[] args) {
    Thread first = new TryThread("A ", "a ", 200L);
    Thread second = new TryThread("B ", "b ", 300L);
    Thread third = new TryThread("C ", "c ", 500L);
    first.start();//from w  w  w .j  a va2s  . c o  m
    second.start();
    third.start();
    try {
        Thread.sleep(3000);
        first.interrupt();
        second.interrupt();
        third.interrupt();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:SleepInterrupt.java

public static void main(String[] args) {
    SleepInterrupt si = new SleepInterrupt();
    Thread t = new Thread(si);
    t.start();/*from   w w w.j  av a2  s.co  m*/

    // Be sure that the new thread gets a chance to
    // run for a while.
    try {
        Thread.sleep(2000);
    } catch (InterruptedException x) {
    }

    System.out.println("in main() - interrupting other thread");
    t.interrupt();
    System.out.println("in main() - leaving");
}

From source file:gridool.GridMain.java

public static void main(String[] args) {
    final Thread parent = Thread.currentThread();
    final GridServer grid = new GridServer();
    try {//  w ww. ja v a2s  .  com
        grid.start();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                parent.interrupt();
            }
        });
    } catch (InternalException ie) {
        shutdown(grid, ie);
    } catch (Throwable e) {
        shutdown(grid, e);
    }
    try {
        Thread.currentThread().join();
    } catch (InterruptedException e) {
        ;
    } finally {
        try {
            grid.shutdown(true);
        } catch (RemoteException re) {
            ;
        }
    }
}

From source file:org.atc.Main.java

public static void main(String[] args) throws NamingException, ATCException, FileNotFoundException,
        InterruptedException, ParseException, NoSuchFieldException, IllegalAccessException {

    Options options = createOptions();//ww w . j a  v  a  2s  . com
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args, false);

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

    String configFilePath;
    if (cmd.hasOption("c")) {
        configFilePath = cmd.getOptionValue("c");
    } else {
        configFilePath = System.getProperty("user.dir") + "/conf/client.yaml";
    }

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

    startStatReporting(config);

    int subscriberCount = config.getTopicSubscribers().size() + config.getQueueSubscribers().size()
            + config.getDurableTopicSubscribers().size();
    final List<Thread> threadList = new ArrayList<Thread>(subscriberCount);

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

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

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

    TimeUnit.SECONDS.sleep(config.getPublisherInitialDelaySeconds());

    // Publishers
    AMQPTopicPublisher topicPublisher;
    for (PublisherConfig publisherConfig : config.getTopicPublishers()) {
        topicPublisher = new AMQPTopicPublisher();
        topicPublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(topicPublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

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

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            log.info("Shutting down test client.");
            slf4jReporter.report();
            csvGaugeReporter.report();
            reporter.report();
            if (null != jmxReporter) {
                jmxReporter.close();
            }
            if (null != csvReporter) {
                csvReporter.report();
                csvReporter.close();
            }
            for (Thread t : threadList) {
                t.interrupt();
            }
        }
    });

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

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

From source file:jms.Main.java

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

    Options options = createOptions();// www .  ja v a  2s.  c  om

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

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

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

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

    startStatReporting(config.getGlobalConfig());

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

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

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

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

    // Publishers

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

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

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

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

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

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

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

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