public class TestStopThread {
public static void main(String[] args) throws InterruptedException {
StopThread st = new StopThread();
st.setName("线程st");
st.start();
Thread.sleep(3000);
st.stopFlag();
Thread.sleep(1000);
System.out.println(st.getState());
}
}
class StopThread extends Thread {
// 此变量必须加上volatile
private volatile boolean stop = false;
@Override
public void run() {
// 判断线程体是否运行
while (!stop) {
System.out.println("线程StopThread正在运行");
long time = System.currentTimeMillis();
/*
* 使用while循环模拟 sleep 方法,这里不要使用sleep,否则在阻塞时会抛
* InterruptedException异常而退出循环,这样while检测stop条件就不会执行,
* 失去了意义。
*/
while ((System.currentTimeMillis() - time < 1000)) {}
}
System.out.println("线程StopThread正在结束");
}
// 线程终止
public void stopFlag() {
stop = true;
}
}
public class TestInterrupt1 {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
t.interrupt();
System.out.println("调用线程的interrupt()方法");
System.out.println("线程的中断状态:" +t.isInterrupted());
}
static class MyThread extends Thread {
public void run() {
long time = System.currentTimeMillis();
System.out.println("线程正在运行");
/*
* 使用while循环模拟 sleep 方法,这里不要使用sleep,否则在阻塞时会抛
* InterruptedException异常而退出循环。
*/
while ((System.currentTimeMillis() - time < 1000)) {}
System.out.println("线程的中断状态:" + Thread.interrupted());
System.out.println("线程的中断状态被清除:" +isInterrupted());
while ((System.currentTimeMillis() - time < 5000)) {}
System.out.println("线程运行完成");
}
}
}
调用线程的interrupt()方法 线程正在运行 线程的中断状态:true 线程的中断状态:true 线程的中断状态被清除:false 线程运行完成
public class InterruptTest extends Thread{
public static void main(String[] args) throws InterruptedException {
InterruptTest t=new InterruptTest();
t.start();
Thread.sleep(1000);
t.interrupt();
}
public void run(){
while(!Thread.interrupted()){
System.out.println("Thread is running.....");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有