java 停止线程:如何使用Java停止线程

Java中停止线程的方法有两种:一种是使用Thread.interrupt()方法,另一种是使用volatile boolean变量。

Java中停止线程的方法有两种:一种是使用Thread.interrupt()方法,另一种是使用volatile boolean变量。

Java中停止线程的方法有两种:一种是使用Thread.interrupt()方法,另一种是使用volatile boolean变量。

1. 使用Thread.interrupt()方法:

Thread.interrupt()方将线程的中断标志设置为true,从而使线程停止执行。

代码示例:

public class MyThread extends Thread {

@Override

public void run() {

while (!Thread.currentThread().isInterrupted()) {

System.out.println("MyThread is running...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}

}

}

// 停止线程

MyThread.interrupt();

2. 使用volatile boolean变量:

使用volatile boolean变量来控制线程的运行状态,当变量值为false时,线程停止执行;当变量值为true时,线程继续执行。

代码示例:

public class MyThread extends Thread {

private volatile boolean running = true;

@Override

public void run() {

while (running) {

System.out.println("MyThread is running...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

// 停止线程

public void stopThread() {

running = false;

}

}

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(651)
java 释放对象:如何使用 Java 垃圾回收机制来释放对象
上一篇
java单元测试覆盖率:如何提高Java单元测试覆盖率
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(71条)