Interrupt sleeping thread

An attempt to abort the current thread, in this example, t1, which is executed by the thread in the thread pool.

t2 is the one that sends the interrupt.

I can not stop the start of t1, t1 does not get an InterruptedException.

What am I missing?

    Executor exec1 = Executors.newFixedThreadPool(1);

    // task to be interrupted
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("starting uninterruptible task 1");
                Thread.sleep(4000);
                System.out.println("stopping uninterruptible task 1");
            } catch (InterruptedException e) {
                assertFalse("This line should never be reached.", true);
                e.printStackTrace();
            }               
        }           
    };
    final Thread t1 = new Thread(runnable);


    // task to send interrupt
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                t1.interrupt();
                System.out.println("task 2 - Trying to stop task 1");
                Thread.sleep(5000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }               
        }           
    };
    Thread t2 = new Thread(runnable2);

    exec1.execute(t1);
            t2.start();
    t2.join();
+5
source share
5 answers

, . runnables, (t2), t1 Executor . Thread - Runnable. Executor - (, ), ( ) . , Runnable ( Thread). , , .

, , Executor .

+3

, Thread ThreadPool.

, Thread Runnable, Runnable Thread, , #interrupt() won ' t .

, , FutureTask. Runnable FutureTask, . , , futureTask.cancel(true).

+3

, , Executor .

Thread, , . , t1 - , . t1.interrupt() .

ExecutorService submit() Runnable/Callable. a Future, cancel(), .

+1

,

final ExecutorService exec1 = Executors.newFixedThreadPool(1);
final Future<?> f = exec1.submit(runnable);
...
f.cancel(true);
0

Thread.interrupt InterruptedException. , Thread.interrupted() Thread.isInterrupted.

. http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#interrupt().

0

All Articles