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:org.apache.helix.userdefinedrebalancer.LockManagerDemo.java

/**
 * LockManagerDemo clusterName, numInstances, lockGroupName, numLocks
 * @param args//from  w  ww .  j  a v a2s  .c om
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    final String zkAddress = "localhost:2199";

    // default participant parameters in case the config does not specify them
    int numInstances = 3;
    boolean instancesSpecified = false;
    Thread[] processArray = new Thread[numInstances];

    // HelixManager for setting up the controller
    HelixManager controllerManager = null;

    // Name of the lock group resource (specified by the config file)
    String lockGroupName = null;
    try {
        startLocalZookeeper(2199);
        YAMLClusterSetup setup = new YAMLClusterSetup(zkAddress);
        InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("lock-manager-config.yaml");
        final YAMLClusterSetup.YAMLClusterConfig config = setup.setupCluster(input);
        if (config == null) {
            LOG.error("Invalid YAML configuration");
            return;
        }
        if (config.resources == null || config.resources.isEmpty()) {
            LOG.error("Need to specify a resource!");
            return;
        }

        // save resource name
        lockGroupName = config.resources.get(0).name;

        // save participants if specified
        if (config.participants != null && config.participants.size() > 0) {
            numInstances = config.participants.size();
            instancesSpecified = true;
            processArray = new Thread[numInstances];
        }

        // run each participant
        for (int i = 0; i < numInstances; i++) {
            String participantName;
            if (instancesSpecified) {
                participantName = config.participants.get(i).name;
            } else {
                participantName = "localhost_" + (12000 + i);
            }
            final String instanceName = participantName;
            processArray[i] = new Thread(new Runnable() {

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

                    try {
                        lockProcess = new LockProcess(config.clusterName, zkAddress, instanceName,
                                config.resources.get(0).stateModel.name);
                        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);

        // start the controller
        controllerManager = HelixControllerMain.startHelixController(zkAddress, config.clusterName,
                "controller", HelixControllerMain.STANDALONE);
        Thread.sleep(5000);

        // HelixAdmin for querying cluster state
        HelixAdmin admin = new ZKHelixAdmin(zkAddress);

        printStatus(admin, config.clusterName, lockGroupName);

        // stop one participant
        System.out.println("Stopping the first participant");
        processArray[0].interrupt();
        Thread.sleep(3000);
        printStatus(admin, config.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: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  .ja  v  a  2 s  .  c  o  m
    second.start();
    third.start();
    try {
        Thread.sleep(3000);
    } catch (Exception e) {
        System.out.println(e);
    }
    first.interrupt();
    second.interrupt();
    third.interrupt();
    if (first.isInterrupted()) {
        System.out.println("First thread has been interrupted.");
    }
}

From source file:EarlyNotify.java

public static void main(String[] args) {
    final EarlyNotify enf = new EarlyNotify();

    Runnable runA = new Runnable() {
        public void run() {
            try {
                String item = enf.removeItem();
                print("returned: '" + item + "'");
            } catch (InterruptedException ix) {
                print("interrupted!");
            } catch (Exception x) {
                print("threw an Exception!!!\n" + x);
            }/*from  www .  j a  va 2s.c  om*/
        }
    };

    Runnable runB = new Runnable() {
        public void run() {
            enf.addItem("Hello!");
        }
    };

    try {
        Thread threadA1 = new Thread(runA, "A");
        threadA1.start();

        Thread.sleep(500);

        Thread threadA2 = new Thread(runA, "B");
        threadA2.start();

        Thread.sleep(500);

        Thread threadB = new Thread(runB, "C");
        threadB.start();

        Thread.sleep(1000);

        threadA1.interrupt();
        threadA2.interrupt();
    } catch (InterruptedException x) {
    }
}

From source file:org.apache.hadoop.hdfs.fsshellservice.FsShellServiceImpl.java

public static void main(String[] args) {
    FsShellServiceImpl imp = new FsShellServiceImpl(new Configuration());
    Thread t = new Thread(imp);
    t.start();//  w ww . j ava  2  s . c om
    while (true) {
        try {
            t.join();
            break;
        } catch (InterruptedException e) {
            t.interrupt();
        }
    }
}

From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainer.java

/**
 * Allows to run the standalone processing unit container. Uses the {@link
 * StandaloneProcessingUnitContainerProvider} and the parameters provided in order to configure
 * it./*from   ww  w . j  a  v a2 s.  com*/
 *
 * <p> The following parameters are allowed: <ul> <li><b>[location]</b>: The location of the
 * processing unit archive. See {@link org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider#StandaloneProcessingUnitContainerProvider(String)}.
 * This parameter is required and must be at the end of the command line.</li> <li><b>-config
 * [configLocation]</b>: Allows to add a Spring application context config location. See {@link
 * org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider#addConfigLocation(String)}.
 * This is an optional parameter and it can be provided multiple times.</li> <li><b>-properties
 * [beanName] [properties]</b>: Allows to inject {@link org.openspaces.core.properties.BeanLevelProperties},
 * see {@link org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider#setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)}.
 * [beanName] is optional, if not used, the properties will set the {@link
 * org.openspaces.core.properties.BeanLevelProperties#setContextProperties(java.util.Properties)}.
 * If used, will inject properties only to the bean registered under the provided beanName
 * within the Spring context (see {@link org.openspaces.core.properties.BeanLevelProperties#setBeanProperties(String,
 * java.util.Properties)}). The [properties] can either start with <code>embed://</code> which
 * mean they will be provided within the command line (for example:
 * <code>embed://propName1=propVal1;propName2=propVal2</code>) or they can follow Spring {@link
 * org.springframework.core.io.Resource} lookup based on URL syntax or Spring extended
 * <code>classpath</code> prefix (see {@link org.springframework.core.io.DefaultResourceLoader}).</li>
 * <li><b>-cluster [cluster parameters]</b>: Allows to configure {@link
 * org.openspaces.core.cluster.ClusterInfo}, see {@link org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider#setClusterInfo(org.openspaces.core.cluster.ClusterInfo)}.</li>
 * The following parameters are allowed: <code>total_members=1,1</code> (1,1 is an example
 * value), <code>id=1</code> (1 is an example value), <code>backup_id=1</code> (1 is an example
 * value) and <code>schema=primary_backup</code> (primary_backup is an example value). No
 * parameter is required. For more information regarding the Space meaning of this parameters
 * please consult GigaSpaces reference documentation within the Space URL section. </ul>
 */
public static void main(String[] args) throws Exception {
    GSLogConfigLoader.getLoader();
    showUsageOptionsOnHelpCommand(args);
    if (args.length == 0) {
        printUsage();
        System.exit(1);
    }

    logger.info("Starting with args: " + Arrays.toString(args) + "\n"
            + RuntimeInfo.getEnvironmentInfoIfFirstTime());
    try {
        final ProcessingUnitContainer container = createContainer(args);
        logger.info("Started successfully");

        // Use the MAIN thread as the non daemon thread to keep it alive
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    logger.info("Shutdown hook triggered");
                    container.close();
                    logger.info("Shutdown complete");
                } finally {
                    mainThread.interrupt();
                }
            }
        });
        while (!mainThread.isInterrupted()) {
            try {
                Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {
                // do nothing, simply exit
            }
        }
    } catch (Exception e) {
        printUsage();
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:TransitionDetectorMain.java

public static void main(String[] args) {
    try {//from  www.j a v  a2s.  c  o  m
        TransitionDetector td = new TransitionDetector(false);

        Thread threadA = startTrueWaiter(td, "threadA");
        Thread threadB = startFalseWaiter(td, "threadB");

        Thread.sleep(200);
        print("td=" + td + ", about to set to 'false'");
        td.setValue(false);

        Thread.sleep(200);
        print("td=" + td + ", about to set to 'true'");
        td.setValue(true);

        Thread.sleep(200);
        print("td=" + td + ", about to pulse value");
        td.pulseValue();

        Thread.sleep(200);
        threadA.interrupt();
        threadB.interrupt();
    } catch (InterruptedException x) {
        x.printStackTrace();
    }
}

From source file:org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainer.java

/**
 * Allows to run the integrated processing unit container. Uses the {@link
 * org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider} and the
 * parameters provided in order to configure it. <p/> <p/> The following parameters are allowed:
 * <ul> <li><b>-config [configLocation]</b>: Allows to add a Spring application context config
 * location. See {@link org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider#addConfigLocation(String)}.
 * This is an optional parameter and it can be provided multiple times.</li> <li><b>-properties
 * [beanName] [properties]</b>: Allows to inject {@link org.openspaces.core.properties.BeanLevelProperties},
 * see {@link org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider#setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)}.
 * [beanName] is optional, if not used, the properties will set the {@link
 * org.openspaces.core.properties.BeanLevelProperties#setContextProperties(java.util.Properties)}.
 * If used, will inject properties only to the bean registered under the provided beanName
 * within the Spring context (see {@link org.openspaces.core.properties.BeanLevelProperties#setBeanProperties(String,
 * java.util.Properties)}). The [properties] can either start with <code>embed://</code> which
 * mean they will be provided within the command line (for example:
 * <code>embed://propName1=propVal1;propName2=propVal2</code>) or they can follow Spring {@link
 * org.springframework.core.io.Resource} lookup based on URL syntax or Spring extended
 * <code>classpath</code> prefix (see {@link org.springframework.core.io.DefaultResourceLoader}).</li>
 * <li><b>-cluster [cluster parameters]</b>: Allows to configure {@link
 * org.openspaces.core.cluster.ClusterInfo}, see {@link org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider#setClusterInfo(org.openspaces.core.cluster.ClusterInfo)}.</li>
 * The following parameters are allowed: <code>total_members=1,1</code> (1,1 is an example
 * value), <code>id=1</code> (1 is an example value), <code>backup_id=1</code> (1 is an example
 * value) and <code>schema=primary_backup</code> (primary_backup is an example value). No
 * parameter is required. For more information regarding the Space meaning of this parameters
 * please consult GigaSpaces reference documentation within the Space URL section. </ul>
 *///from  w ww. ja  v  a  2s  . c o  m
public static void main(String[] args) throws Exception {
    GSLogConfigLoader.getLoader();

    //when calling with space-instance script, and no arguments were passed, we concatenate --help
    //IntegratedProcessingUnitContainer can also run without arguments and load pu.xml
    showUsageOptionsOnHelpCommand(args);

    logger.info("Starting with args: " + Arrays.toString(args) + "\n"
            + RuntimeInfo.getEnvironmentInfoIfFirstTime());
    try {
        final ProcessingUnitContainer container = createContainer(args);
        logger.info("Started successfully");

        // Use the MAIN thread as the non daemon thread to keep it alive
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    logger.info("Shutdown hook triggered");
                    container.close();
                    logger.info("Shutdown complete");
                } finally {
                    mainThread.interrupt();
                }
            }
        });
        while (!mainThread.isInterrupted()) {
            try {
                Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {
                // do nothing, simply exit
            }
        }
    } catch (Exception e) {
        printUsage();
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:Deadlock.java

public static void main(String[] args) {
    final Deadlock obj1 = new Deadlock("Thread 1");
    final Deadlock obj2 = new Deadlock("Thread 2");

    Runnable runA = new Runnable() {
        public void run() {
            obj1.checkOther(obj2);/*from  www  .j a va  2 s .c  o m*/
        }
    };

    Thread thread = new Thread(runA, "A");
    thread.start();

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

    Runnable runB = new Runnable() {
        public void run() {
            obj2.checkOther(obj1);
        }
    };

    Thread threadB = new Thread(runB, "B");
    threadB.start();

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

    threadPrint("finished sleeping");

    threadPrint("about to interrupt() threadA");
    thread.interrupt();

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

    threadPrint("about to interrupt() threadB");
    threadB.interrupt();

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

    threadPrint("did that break the deadlock?");
}

From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA",
            "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY");

    final String endpoint = "sqs.us-west-2.amazonaws.com";
    final String queueName = "image";
    final int producerCount = 10;
    final int consumerCount = 3;
    final int batchSize = 3;
    final int messageSizeByte = 10000;
    final int runTimeMinutes = 100;

    // configure the SQS client with enough connections for all producer and
    // consumer threads
    AmazonSQS sqsClient = new AmazonSQSClient(credentials,
            new ClientConfiguration().withMaxConnections(producerCount + consumerCount));
    sqsClient.setEndpoint(endpoint);// w  w w .  j av a2 s.  co m
    String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();

    // the flag to stop producer, consumer, and monitor threads
    AtomicBoolean stop = new AtomicBoolean(false);

    // start the producers
    final AtomicInteger producedCount = new AtomicInteger();
    Thread[] producers = new Thread[producerCount];
    for (int i = 0; i < producerCount; i++) {
        producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop);
        producers[i].start();
    }

    // start the consumers
    final AtomicInteger consumedCount = new AtomicInteger();
    Thread[] consumers = new Thread[consumerCount];
    for (int i = 0; i < consumerCount; i++) {
        consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop);
        consumers[i].start();
    }

    // start the monitor (thread)
    Thread monitor = new Monitor(producedCount, consumedCount, stop);
    monitor.start();

    // wait for the specified amount of time then stop
    Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES)));
    stop.set(true);

    // join all threads
    for (int i = 0; i < producerCount; i++)
        producers[i].join();

    for (int i = 0; i < consumerCount; i++)
        consumers[i].join();

    monitor.interrupt();
    monitor.join();
}

From source file:com.dxc.temp.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    int argIndex = 0;

    final String accessKey = args[argIndex++];
    final String secretKey = args[argIndex++];
    final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    final String endpoint = args[argIndex++];
    final String queueName = args[argIndex++];
    final int producerCount = Integer.parseInt(args[argIndex++]);
    final int consumerCount = Integer.parseInt(args[argIndex++]);
    final int batchSize = Integer.parseInt(args[argIndex++]);
    final int messageSizeByte = Integer.parseInt(args[argIndex++]);
    final int runTimeMinutes = Integer.parseInt(args[argIndex++]);

    // configure the SQS client with enough connections for all producer and
    // consumer threads
    AmazonSQS sqsClient = new AmazonSQSClient(credentials,
            new ClientConfiguration().withMaxConnections(producerCount + consumerCount));
    sqsClient.setEndpoint(endpoint);//from   www  .  j  av  a2  s  .c om
    String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();

    // the flag to stop producer, consumer, and monitor threads
    AtomicBoolean stop = new AtomicBoolean(false);

    // start the producers
    final AtomicInteger producedCount = new AtomicInteger();
    Thread[] producers = new Thread[producerCount];
    for (int i = 0; i < producerCount; i++) {
        if (batchSize == 1)
            producers[i] = new Producer(sqsClient, queueUrl, messageSizeByte, producedCount, stop);
        else
            producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount,
                    stop);
        producers[i].start();
    }

    // start the consumers
    final AtomicInteger consumedCount = new AtomicInteger();
    Thread[] consumers = new Thread[consumerCount];
    for (int i = 0; i < consumerCount; i++) {
        if (batchSize == 1)
            consumers[i] = new Consumer(sqsClient, queueUrl, consumedCount, stop);
        else
            consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop);
        consumers[i].start();
    }

    // start the monitor (thread)
    Thread monitor = new Monitor(producedCount, consumedCount, stop);
    monitor.start();

    // wait for the specified amount of time then stop
    Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES)));
    stop.set(true);

    // join all threads
    for (int i = 0; i < producerCount; i++)
        producers[i].join();

    for (int i = 0; i < consumerCount; i++)
        consumers[i].join();

    monitor.interrupt();
    monitor.join();
}