<强> Java中终止线程的方式主要有三种:强>
1,使用停止()方法,已被弃用。原因是:停止()是立即终止,会导致一些数据被到处理一部分就会被终止,而用户并不知道哪些数据被处理,哪些没有被处理,产生了不完整的“残疾”数据,不符合完整性,所以被废弃,所以,算了吧!
2,使用不稳定的标志位
看一个简单的例子:
首先,实现一个可运行的接口,在其中定义不稳定的标志位,在运行()方法中使用标志位控制程序运行
公共类MyRunnable实现Runnable {//定义退出标志,真会一直执行,假的会退出循环//使用不稳定的目的是保证可见性,一处修改了标志,处处都要去主存读取新的值,而不是使用缓存 公众不稳定的布尔标志=true; 公共空间run () { system . out。println("第" + Thread.currentThread () . getname() +“个线程创建”); 尝试{ thread . sleep (1000 l); }捕捉(InterruptedException e) { e.printStackTrace (); }//退出标志生效位置 而(国旗){ } system . out。println("第" + Thread.currentThread () . getname() +“个线程终止”); } } >之前然后,在main()方法中创建线程,在合适的时候,修改标志位,终止运行中的线程。
公开课TreadTest { 公共静态void main (String[]参数)抛出InterruptedException { MyRunnable runnable=new MyRunnable ();//创建3个线程 for (int i=1;我& lt;=3;我+ +){ 线程的线程=新线程(runnable,我+ " "); thread.start (); }//线程休眠 thread . sleep (2000 l); System.out.println (“- - - - - - - - - - - - - - - - - - - - - - - - - - - -”);//修改退出标志,使线程终止 可运行。国旗=false; } } >之前最后,运行结果,如下:
第1个线程创建 第2个线程创建 第3个线程创建 -------------------------- 第3个线程终止 第1个线程终止 第2个线程终止 >之前3,使用中断()中断的方式,注意使用中断()方法中断正在运行中的线程只会修改中断状态位,可以通过isInterrupted()判断。如果使用中断()方法中断阻塞中的线程,那么就会抛出InterruptedException异常,可以通过捉捕获异常,然后进行处理后终止线程。有些情况,我们不能判断线程的状态,所以使用中断()方法时一定要慎重考虑。
<强>第一种:正在运行中终止强>
公共类MyThread扩展线程{ 公共空间run () { super.run (); 尝试{ for (int i=0;i<500000;我+ +){ 如果(this.interrupted ()) { system . out。println(“线程已经终止,为循环不再执行”); 抛出InterruptedException (); } System.out.println(“我=" + (i + 1)); } System.out.println(“这是为循环外面的语句,也会被执行”); }捕捉(InterruptedException e) { System.out.println(“进入MyThread.java类中的赶上了…”); e.printStackTrace (); } } } >之前公共类运行{ 公共静态void main (String参数[]){ 线程的线程=new MyThread (); thread.start (); 尝试{ thread . sleep (2000); thread.interrupt (); }捕捉(InterruptedException e) { e.printStackTrace (); } } } >之前运行结果如下:
… 我=203798 我=203799 我=203800 线程已经终止,循环不再执行 进入MyThread.java类中的赶上了…… java.lang.InterruptedException 在thread.MyThread.run (MyThread.java: 13) >之前<强>第二种:阻塞状态(睡眠,等待等)终止强>
公共类MyThread扩展线程{ 公共空间run () { super.run (); 尝试{ System.out.println(“线程开始…”); thread . sleep (200000); System.out.println(“线程结束。”); }捕捉(InterruptedException e) { system . out。println(“在沉睡中被停止,进入,调用isInterrupted()方法的结果是:”+ this.isInterrupted ()); e.printStackTrace (); } } } >之前线程开始… 在沉睡中被停止,进入,调用isInterrupted()方法的结果是:假的 . lang。InterruptedException:睡眠中断 在java.lang.Thread。睡眠(本地方法) thread.MyThread.run (MyThread.java: 12)Java中终止线程的方法详解