能停止的线程——异常法(菜鸟玩线程)

能停止的线程_异常法

在线程中用for循环语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可。

实现代码如下:

自定义线程类
package com.thread5;

public class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                if (this.interrupted()) {
                    System.out.println("已经是停止状态了!我要退出了!");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
            //判断该代码是否执行//
            System.out.println("我在for下面");
            
        } catch (InterruptedException e) {
            System.out.println("进MyThread.java类run方法中的catch了");
            e.printStackTrace();
        }
    }
}

启动类
package com.thread5;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Run {
    public static void main(String[] args) {
        //控制台输出值文件
        File f = new File("out.txt");
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        PrintStream printStream = new PrintStream(fileOutputStream);
        System.setOut(printStream);
        
        //线程开启
        try {
            MyThread myThread = new MyThread();
            myThread.start();
            Thread.sleep(2000);
            myThread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!!");
    }
}

执行结果
i=159845
i=159846
i=159847
i=159848
i=159849
i=159850
i=159851
i=159852
i=159853
i=159854
i=159855
i=159856
i=159857
i=159858
i=159859
i=159860
end!!
已经是停止状态了!我要退出了!
进MyThread.java类run方法中的catch了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值