/*
sleep,阻塞当前线程,腾出CPU,让给其他线程
单位是毫秒
静态方法
*/
public class ThreadTest04
{
public static void main(String[] args)
{
Thread t1 = new Processor();
t1.setName("t1");
t1.start();
}
} class Processor extends Thread
{
//Thread的run方法不抛出异常,在run方法的声明位置上不能使用throws,只能try...catch...
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--->"+i);
try{
Thread.sleep(1000); //阻塞1s
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
/*
更好地终止一个正在执行的线程
需求:线程启动5s后终止
*/
public class ThreadTest04
{
public static void main(String[] args) throws Exception
{
Processor p = new Processor();
Thread t1 = new Thread(p);
t1.setName("t1");
t1.start(); Thread.sleep(5000);
p.isRun = false;
}
} class Processor implements Runnable
{
boolean isRun = true;
public void run(){
for(int i=0;i<10;i++){
try{
if(isRun){
System.out.println(Thread.currentThread().getName()+"--->"+i);
Thread.sleep(1000);
}else{
return;
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}