小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
8、interrupt()
中断线程.注意调用 interrupt()方法仅仅是在当前线程打一个停止标志,并不是真正的停止线程
package com.wkcto.threadmehtod.p7interrupt;
/**
* Author : 老崔
*/
public class SubThread2 extends Thread {
@Override
public void run() {
super.run();
for(int i = 1; i <= 10000; i++){
//判断线程的中断标志,线程有 isInterrupted()方法,该
方法返回线程的中断标志
if ( this.isInterrupted() ){
System.out.println("当前线程的中断标志为 true,
我要退出了");
//
break;
//中断循环, run()方法体执行完毕,
子线程运行完毕
return;
//直接结束当前 run()方法的执行
}
System.out.println("sub thread --> " + i);
}
}
}
package com.wkcto.threadmehtod.p7interrupt;
/**
* Author : 老崔
*/
public class Test02 {
public static void main(String[] args) {
SubThread2 t1 = new SubThread2();
t1.start();
///开启子线程
//当前线程是 main 线程
for(int i = 1; i<=100; i++){
System.out.println("main ==> " + i);
}
//中断子线程
t1.interrupt();
////仅仅是给子线程标记中断,
}
}
9、setDaemon()
Java 中的线程分为用户线程与守护线程
守护线程是为其他线程提供服务的线程,如垃圾回收器(GC)就是一个典型的守护线程
守护线程不能单独运行, 当 JVM 中没有其他用户线程,只有守护线程时,守护线程会自动销毁, JVM 会退出
package com.wkcto.threadmehtod.p8daemon;
/**
* Author : 老崔
*/
public class SubDaemonThread extends Thread {
@Override
public void run() {
super.run();
while(true){
System.out.println("sub thread.....");
}
}
}
package com.wkcto.threadmehtod.p8daemon;
/**
* 设置线程为守护线程
* Author : 蛙课网老崔
*/
public class Test {
public static void main(String[] args) {
SubDaemonThread thread = new SubDaemonThread();
//设置线程为守护线程
thread.setDaemon(true);
//设置守护线程的代码应
该在线程启动前
thread.start();
//当前线程为 main 线程
for(int i = 1; i <= 10 ; i++){
System.out.println("main== " + i);
}
//当 main 线程结束, 守护线程 thread 也销毁了
}
}
下一篇开始说说线程的生命周期
线程的生命周期是线程对象的生老病死,即线程的状态
线程生命周期可以通过 getState()方法获得, 线程的状态是Thread.State 枚举类型定义的,