Android知识Android开发Android技术知识

Java多线程之线程中断

2017-05-10  本文已影响97人  Showdy

取消任务的方式

Java中没有提供任何机制来安全地终止线程,但是提供了中断(Interruption)协作机制,能够使一个线程终止另一个线程的当前工作. 一般取消或停止某个任务,很少采用立即停止,因为立即停止会使得共享数据结构出于不一致的状态.这也是Thread.stop(),Thread.suspend()以及Thread.resume()不安全的原因而废弃.

Java中有三种方式可以终止当前运行的线程:

使用中断标记来中断线程.


    public class PrimeGenerator implements Runnable {
        private static ExecutorService exec = Executors.newCachedThreadPool();
    
        @GuardedBy("this") private final List<BigInteger> primes
                = new ArrayList<BigInteger>();
        private volatile boolean cancelled;
    
        public void run() {
            BigInteger p = BigInteger.ONE;
            while (!cancelled) {
                p = p.nextProbablePrime();
                synchronized (this) {
                    primes.add(p);
                }
            }
        }
    
        public void cancel() {
            cancelled = true;
        }
    
        public synchronized List<BigInteger> get() {
            return new ArrayList<BigInteger>(primes);
        }
    
        static List<BigInteger> aSecondOfPrimes() throws InterruptedException {
            PrimeGenerator generator = new PrimeGenerator();
            exec.execute(generator);
            try {
                SECONDS.sleep(1);
            } finally {
                generator.cancel();
            }
            return generator.get();
        }
    }

设置标记的中断策略: PrimeGenerator使用一种简单取消策略,客户端代码通过调研cancel来请求取消,PrimeGenerator在每次搜索素数时前先检查是否存在取消请求,如果不存在就退出.

但是使用设置标记的中断策略有一问题: 如果任务调用调用阻塞的方法,比如BlockingQueue.put,那么可能任务永远不会检查取消标记而不会结束.


    class BrokenPrimeProducer extends Thread {
        private final BlockingQueue<BigInteger> queue;
        private volatile boolean cancelled = false;
    
        BrokenPrimeProducer(BlockingQueue<BigInteger> queue) {
            this.queue = queue;
        }
    
        public void run() {
            try {
                BigInteger p = BigInteger.ONE;
                while (!cancelled)
                    //此处阻塞,可能永远无法检测到结束的标记
                    queue.put(p = p.nextProbablePrime());
            } catch (InterruptedException consumed) {
            }
        }
    
        public void cancel() {
            cancelled = true;
        }
    }

解决办法也很简单: 使用中断而不是使用boolean标记来请求取消

使用中断(Interruption)请求取消

故而上面问题的解决方案如下:


    public class PrimeProducer extends Thread {
        private final BlockingQueue<BigInteger> queue;
    
        PrimeProducer(BlockingQueue<BigInteger> queue) {
            this.queue = queue;
        }
    
        public void run() {
            try {
                BigInteger p = BigInteger.ONE;
                while (!Thread.currentThread().isInterrupted())
                    queue.put(p = p.nextProbablePrime());
            } catch (InterruptedException consumed) {
                /* Allow thread to exit */
            }
        }
    
        public void cancel() {
            interrupt();
        }
    }

上一篇下一篇

猜你喜欢

热点阅读