线程的中断


以往有的时候会使用stop()方法停止线程,但是JDK早就已经废除了stop()方法,不建议使用stop()方法来停止一个线程的运行。
下面有两种方法实现线程的中断:

一:异常处理

/*
使用两种方法使程序中断
*/
/*1异常处理:package THREAD;

class Test extends Thread {
    public void run() {
            try {
                Thread.sleep(100000000);
                System.out.println("HelloWorld");
            } catch (InterruptedException e) {
              e.printStackTrace();
            }

        for(int i=0;i<10;i++)
        {
            System.out.println(Thread.currentThread().getName() + "-->"+i);
        }
    }
}这个意思就是先让程序一直睡眠,如果睡眠到了时间以后输出HelloWorld,使用中断让这个程序中断然后执行下面的for语句
  public class interrupt {
        public static void main(String[] args) throws InterruptedException {
            Thread test = new Test();
                test.start();//启动线程
                 Thread.sleep(5000);
                test.interrupt();//执行中断
            }
        }*/

执行结果如下所示:
由于 Thread.sleep(100000000);睡眠时间太长了,CPU想执行其他的程序,就使用 test.interrupt();//执行中断,去执行下面的for语句就运行如下结果。

Thread-0-->0
Thread-0-->1
Thread-0-->2
Thread-0-->3
Thread-0-->4
Thread-0-->5
Thread-0-->6
Thread-0-->7
Thread-0-->8
Thread-0-->9

二:布尔值

//2:布尔值

package THREAD;
class Test implements  Runnable{
    boolean run=true;
    public void run() {
        for(int i=0;i<10;i++)
        {
            if(run)
            {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "-->"+i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else return;
        }
    }
}//如果run=true执行程序但是主程序中的 run是false所以先睡眠5秒然后执行重写的run程序
    public class interrupt {
        public static void main(String[] args) throws InterruptedException {
            Test t1=new Test();
            Thread t2 = new Thread(t1);
            t2.start();//启动线程
            Thread.sleep(5000);
            t1.run=false;
            }
        }

运行结果如下所示:

Thread-0-->0
Thread-0-->1
Thread-0-->2
Thread-0-->3
Thread-0-->4

Thread.sleep()主线程休眠5秒,t2线程运行5次,t2执行一次间隔一秒,
所以执行到4.然后由于 t1.run=false;run()方法不能继续执行,所以结果如上所示。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值