不推荐使用JDK提供的stop() destroy()方法
推荐线程自己停下来
建议使用一个标志位进行终止
当flag=fals,则终止
package demo916;
//测试Stop
//建议线程正常停止 利用次数 不建议死循环
// 不要使用stop destroy等过时的方法 或者JDK不建议使用的方法
//因为这些方法有BUG
//
public class TestStop implements Runnable {
//设置一个标志位
boolean flag=true;
@Override
public void run() {
int i=0;
while (flag){
System.out.println("main"+i++);
}
}
//2 设置一个公开的方法停止线程 转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop=new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 100; i++) {
System.out.println("main"+i);
//调用stop方法切换标志位 让线程停止
if (i==70){
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
线程休眠:
sleep(时间)指定当前线程阻塞的毫秒数;
sleep存在异常InterruptedException;
sleep时间到达后线程进入就绪状态;
sleep可以模拟网络延时,倒计时等;
每一个对象都有一个锁,sleep不会释放锁;
public class TestSleep {
public static void main(String[] args) {
Date startTime = new Date(System.currentTimeMillis());//获取当前时间
while (true) {
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}