线程休眠
public static void sleep(long millis)
public class ThreadDemo {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
Thread t1 = new Thread(mr, "时钟");
t1.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
while (true) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(new Date());
System.out.println(Thread.currentThread().getName() + "-----当前时间是:" + dateStr);
try {
Thread.sleep(1000);//休眠10秒
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
中断线程
public final void stop()
public void interrupt()
Thread.interrupt() //中断线程
Thread,isInterrupted()判断是否被中断
Thread.interrupted()判断是否被中断,并清除当前中断状态
/**
*
*子线程休眠10秒
*通过主线程在执行3秒的时候去中断子线程
*/
public class TheadDemo {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
Thread t1 = new Thread(mr);
t1.start();
try {
Thread.sleep(3000);
// t1.stop();
t1.interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("当前时间:" + new Date());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
System.out.println("休眠10的线程被打断了");
System.exit(0);
}
System.out.println("结束时间:" + new Date());
}
}
stop和interrupt的区别
stop会直接将线程生命结束
interrupt会给对应的线程抛出一个异常,
那么对应的线程可以通过InterruptedException来捕获这个异常,并且做出相应的异常处理
注意
stop()方法在现在JDK中不推荐使用,在使用stop()方法时需要自行决定线程何时退出,原因是stop()方法过于暴力,强行把执行到一半的线程终止,可能会引起一些数据不一致的问题.
忘掉Thread.stop方法。虽然它确实停止了一个正在运行的线程,然而,这种方法是不安全也是不受提倡的。
interrupt中断的功能:
1.阻塞状态
当线程由于被调用了sleep(), wait(), join()等方法而进入阻塞状态;若此时调用线程的interrupt()将线程的中断标记设为true。由于处于阻塞状态,中断标记会被清除,同时产生一个InterruptedException异常。将InterruptedException放在适当的为止就能终止线程。
/**
*InterruptedException异常的捕获在whle(true)之内。
*当产生InterruptedException异常时,被catch处理之外,
*仍然在while(true)循环体内;
*要退出while(true)循环体,需要额外的执行退出while(true)的操作。
*/
@Override
public void run() {
while (true) {
try {
// 执行任务...
} catch (InterruptedException ie) {
// InterruptedException在while(true)循环体内。
// 当线程产生了InterruptedException异常时,while(true)仍能继续运行!需要手动退出
break;
}
}
}
2.运行状态
如果线程在运行中,且没有要进入其他状态,操作interrupt()只是会设置线程的中断标志位,没有任何其它作用。
线程应该在运行过程中合适的位置检查中断标志位,比如说,如果主体代码是一个循环,可以在循环开始处进行检查
//当调用阻塞操作时,会因为抛出异常退出,
//当不调用阻塞操作时,会因为检查中断状态而退出
public void run(){
try{
while(!Thread.interrupted()){
// 循环代码
}
System.out.println("Exit normal");
}catch(Exception e){
System.out.println("interrupted");
}
}