设置标记位
class MyThread implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 1;
while(flag){
try {
Thread.sleep(1000);
System.out.println("第"+i+"次执行,线程名称为:"+Thread.currentThread().getName());
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setFlag(boolean flag){
this.flag = flag;
}
}
public class ticket{
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread thread = new Thread(mt,"张一山");
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mt.setFlag(false);
System.out.println("代码结束");
}
}
使用stop()方法强制使线程退出
class MyThread implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 1;
try {
Thread.sleep(1000);
System.out.println("第"+i+"次执行,线程名称为:"+Thread.currentThread().getName());
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ticket{
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread thread = new Thread(mt,"张一山");
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stop();
System.out.println("代码结束");
}
}
使用Thread.interrupt()
class MyThread implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 1;
while(flag){
try {
Thread.sleep(1000);
boolean bool = Thread.currentThread().isInterrupted();
if(bool){
System.out.println("非阻塞情况下执行该操作"+bool);
break;
}
System.out.println("第"+i+"次执行,线程名称为:"+Thread.currentThread().getName());
i++;
} catch (InterruptedException e) {
System.out.println("退出了");
boolean bool = Thread.currentThread().isInterrupted();
System.out.println(bool);
return ;
}
}
}
public void setFlag(boolean flag){
this.flag = flag;
}
}
public class ticket{
public static void main(String[] args)throws InterruptedException {
MyThread mt = new MyThread();
Thread thread = new Thread(mt,"张一山");
thread.start();
Thread.sleep(3000);
thread.interrupt();
System.out.println("代码结束");
}
}