Java多线程学习(1)——停止线程

来源:互联网 发布:sql五表关联 编辑:程序博客网 时间:2024/05/22 05:30

目录:

1.interrupt方法学习(基础知识)

2.异常法

3.sleep法

4.return法

5.stop法(不推荐)


1.interrupt方法学习(基础知识)

调用interrupt方法只是对线程做了一个标记(停止标记),并没有停止线程的效果,需要结合以下两种方法:

1)interrupted():测试当前线程是否已经中断,(静态方法,当前线程是指运行该方法的线程)

如果调用了interrupt()方法,interrupted()返回true,看一个例子:

ThreadTest thread=new ThreadTest();thread.start();thread.interrupt();System.out.println(thread.interrupted());

结果是false,因为interrupted()测试当前线程,而

System.out.println(thread.interrupted());
这行代码执行的当前线程不是thread,该线程没有调用interrupt()方法,也就没有停止标记,所以返回false

再看:

Thread.currentThread().interrupt();
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());

结果为: true false

原因是:调用该方法后,线程的中断状态由该方法清除,也就是说该方法的判断依据是有没有做标记,而调用过后会把这个标记清楚,导致第三行的输出没有标记了,也就false

2)isInterrupted():测试线程是否已经


ThreadTest thread=new ThreadTest();
thread.start();
thread.interrupt();
System.out.println(thread.isInterrupted());

结果为: true,它不会清除中断状态


2.异常法


public class test{
  public static void main(String[] args){  
    ThreadTest thread=new ThreadTest();
    thread.start();
    thread.interrupt();
  }
}

class ThreadTest extends Thread{
  public void run(){
    try{
     for(int i=0;i<100000;i++){
        if(this.interrupted()){
          throw new InterruptedException();
        }
        //code
     }
      //code
   }catch(InterruptedException e){
      //code
    }
  }
}

3.sleep法


如果线程在sleep()状态下停止线程,会进入catch语句,并且清除状态值

public class test{
  public static void main(String[] args){  
    ThreadTest thread=new ThreadTest();
    thread.start();
    thread.interrupt();
  }
}

class ThreadTest extends Thread{
  public void run(){
    try{
     for(int i=0;i<100000;i++){
        //code
     }
     Thread.sleep(10000);
   }catch(InterruptedException e){
      //code
    }
  }
}

代码会执行完for循环中的代码后,进入到catch语句

4.return法


public class test{
  public static void main(String[] args){  
    ThreadTest thread=new ThreadTest();
    thread.start();
    thread.interrupt();
  }
}

class ThreadTest extends Thread{
  public void run(){
     for(int i=0;i<100000;i++){
        if(this.interrupted()){
         return;
        }
        //code
     }
  }
}


5.stop法

调用stop()方法,会暴力中断线程,该方法已作废,原因:

1)有可能使一些收尾工作得不到完成

2)容易出现数据不一致的问题



0 0
原创粉丝点击