public class ThreadSyop {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
//修改线程名字
t.setName("t");
//线程开始
t.start();
//抛出异常
try {
Thread.sleep(5000);//设定为5秒之后线程睡眠
} catch (InterruptedException e) {
e.printStackTrace();
}
//终止线程
//改变run的布尔值,达到终止线程的目的
m4.run = false;
}
}
class MyRunnable implements Runnable{
//设定run的布尔值,成为循环进行的条件
boolean run = true;
//重写run方法
@Override
public void run() {
for(int i = 0;i < 10;i ++ ){
if(run){
System.out.println(Thread.currentThread().getName() + "---" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//终止当前线程
return;
}
}
}
}