java多线程开发 如何正确关闭线程

在java高级开发中,经常会碰到多线程,关于线程的关闭,可能会用stop() 方法,但是stop是线程不安全的,一般采用interrupt,判断线程是否中止采用isInterrupted, 
如果线程中有Thread.sleep方法,当设置中断后,执行这个方法会抛出异常,就务必在异常中继续关闭线程

Thread thread = null;
thread = new Thread(new Runnable() {
    @Override
    public void run() {
        /*
         * 在这里为一个循环,条件是判断线程的中断标志位是否中断
         */
        while (true&&(!Thread.currentThread().isInterrupted())) {
            try {
                Log.i("tag","线程运行中"+Thread.currentThread().getId());
                // 每执行一次暂停40毫秒
                //当sleep方法抛出InterruptedException  中断状态也会被清掉
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
                //如果抛出异常则再次设置中断请求
                Thread.currentThread().interrupt();
            }
        }
    }
});
thread.start();

//触发条件设置中断
thread.interrupt();
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

在java高级开发中,经常会碰到多线程,关于线程的关闭,可能会用stop() 方法,但是stop是线程不安全的,一般采用interrupt,判断线程是否中止采用isInterrupted, 
如果线程中有Thread.sleep方法,当设置中断后,执行这个方法会抛出异常,就务必在异常中继续关闭线程

Thread thread = null;
thread = new Thread(new Runnable() {
    @Override
    public void run() {
        /*
         * 在这里为一个循环,条件是判断线程的中断标志位是否中断
         */
        while (true&&(!Thread.currentThread().isInterrupted())) {
            try {
                Log.i("tag","线程运行中"+Thread.currentThread().getId());
                // 每执行一次暂停40毫秒
                //当sleep方法抛出InterruptedException  中断状态也会被清掉
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
                //如果抛出异常则再次设置中断请求
                Thread.currentThread().interrupt();
            }
        }
    }
});
thread.start();

//触发条件设置中断
thread.interrupt();
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

猜你喜欢

转载自blog.csdn.net/qq_27088383/article/details/80228777