ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

合理提前终止线程

2021-05-04 17:34:12  阅读:13  来源: 互联网

标签:run currentThread Thread 线程 终止 stu6 提前


package com.anyan;

/**
* @author anyan
* @date 2021/5/4-16:07
*/
/*
改进后,终止线程的第二种方法:
*/
public class ThreadEndTest02 {
public static void main(String[] args) {
//Thread t=new Thread();

Student6 stu6=new Student6();
stu6.setName("分支线程");
stu6.start();
for(int j=0;j<30;j++){
for (int i = 0; i <50; i++) {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stu6.run=false;//使分支线程提前终止
}

}
}
class Student6 extends Thread {
boolean run=true;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(run){
// Thread.currentThread().setName("分支线程");
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//在进程终止前save想要保存的内容
System.out.println("分支线程被终止");
return;
}
}
}

}

标签:run,currentThread,Thread,线程,终止,stu6,提前
来源: https://www.cnblogs.com/a-n-yan/p/14729849.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有