1.7.5停止线程(stop方法暴力停止)

来源:互联网 发布:淘宝樱木花道家鞋真吗 编辑:程序博客网 时间:2024/05/16 08:04

package demo;/** * Created by sunyifeng on 17/10/10. */public class MyThread extends Thread {    private int i = 0;    @Override    public void run(){        try {            while (true) {                i++;                System.out.println("i=" + i);                Thread.sleep(1000);            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
package demo;/** * Created by sunyifeng on 17/10/10. */public class Run {    public static void main(String[] args) {        try {            MyThread myThread = new MyThread();            myThread.start();            Thread.sleep(10000);            myThread.stop();        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
运行结果:

i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10

程序分析:

1、不建议使用stop()停止线程,可能使一些清理的工作不能完成;

2、对锁定的对象解锁,导致数据不同步。

原创粉丝点击