1.volatile,不推荐
可以终止
public class Test {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(20);
myRunnable.setFlag(true);
}
}
class MyRunnable implements Runnable {
private volatile boolean flag = false;
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
while (!flag) {
System.out.println("----");
}
}
}
不可以终止
public class Test {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(20);
myRunnable.setFlag(true);
}
}
class MyRunnable implements Runnable {
private volatile boolean flag = false;
private BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);
public void setFlag(boolean flag) {
this.flag = flag;
}
@SneakyThrows
@Override
public void run() {
while (!flag) {
System.out.println("----");
blockingQueue.put("1");
}
}
}
2.interrupt
public class Test {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(10);
thread.interrupt();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("----");
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(100);
thread.interrupt();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
try {
while (true) {
System.out.println("---");
Thread.sleep(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(100);
thread.interrupt();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("---");
// sleep响应中断后,会把interrupt状态清除
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
}