public class MyRunnable implements Runnable {
//定义退出标志,true会一直执行,false会退出循环
//使用volatile目的是保证可见性,一处修改了标志,处处都要去主存读取新的值,而不是使用缓存
public volatile boolean flag = true;
public void run() {
System.out.println("第" + Thread.currentThread().getName() + "个线程创建");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
//退出标志生效位置
while (flag) {
}
System.out.println("第" + Thread.currentThread().getName() + "个线程终止");
}
}
public class TreadTest {
public static void main(String[] arg) throws InterruptedException {
MyRunnable runnable = new MyRunnable();
//创建3个线程
for (int i = 1; i <= 3; i++) {
Thread thread = new Thread(runnable, i + "");
thread.start();
}
//线程休眠
Thread.sleep(2000L);
System.out.println("——————————————————————————");
//修改退出标志,使线程终止
runnable.flag = false;
}
}
第1个线程创建 第2个线程创建 第3个线程创建 -------------------------- 第3个线程终止 第1个线程终止 第2个线程终止
public class MyThread extends Thread {
public void run(){
super.run();
try {
for(int i=0; i<500000; i++){
if(this.interrupted()) {
System.out.println("线程已经终止, for循环不再执行");
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
System.out.println("这是for循环外面的语句,也会被执行");
} catch (InterruptedException e) {
System.out.println("进入MyThread.java类中的catch了。。。");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String args[]){
Thread thread = new MyThread();
thread.start();
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
... i=203798 i=203799 i=203800 线程已经终止, for循环不再执行 进入MyThread.java类中的catch了。。。 java.lang.InterruptedException at thread.MyThread.run(MyThread.java:13)
public class MyThread extends Thread {
public void run(){
super.run();
try {
System.out.println("线程开始。。。");
Thread.sleep(200000);
System.out.println("线程结束。");
} catch (InterruptedException e) {
System.out.println("在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:" + this.isInterrupted());
e.printStackTrace();
}
}
}
线程开始。。。 在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:false java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at thread.MyThread.run(MyThread.java:12)
public class MyThread extends Thread {
public void run(){
super.run();
try {
System.out.println("线程开始。。。");
for(int i=0; i<10000; i++){
System.out.println("i=" + i);
}
Thread.sleep(200000);
System.out.println("线程结束。");
} catch (InterruptedException e) {
System.out.println("先停止,再遇到sleep,进入catch异常");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String args[]){
Thread thread = new MyThread();
thread.start();
thread.interrupt();
}
}
i=9998 i=9999 先停止,再遇到sleep,进入catch异常 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at thread.MyThread.run(MyThread.java:15)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有