1.关于线程的sleep()方法:
static void sleep(long millis)
1:静态方法:Thread.sleep();
2:参数为毫秒
3:作用:让当前线程进入休眠,进入“阻塞状态”
public class myfile{
public static void main(String[] args) {
//让当前主线程进入休眠,睡眠1s
try{
Thread.sleep(1000);//不管对象是谁,出现在main方法中,main线程休眠
}catch(InterruptedException e){
e.printStackTrace();
}
//1s后执行下列代码
System.out.println("java");
}
}
2.sleep睡眠的太久了,怎么叫醒一个正在睡眠的线程?
Thread.interrupt()方法
注意:这个不是终断线程的执行,是终止线程的睡眠
public class myfile{
public static void main(String[] args) {
Thread t=new Thread(new myrunnable());
t.setName("ttt");
//终断线程睡眠
t.start();
t.interrupt();
}
}
class myrunnable implements Runnable{
//run()方法当中的异常不能throws,只能try catch
//因为run()方法在父类没有抛出任何异常,子类不能比父类抛出更多的异常
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->begin");
try{
//这个线程睡眠1年
Thread.sleep(1000*60*60*24*365);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->end");
}
}