欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Stop a thread inside & outside the thread

程序员文章站 2022-03-02 10:48:36
...
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicDemo {

    public static void main(String[] args) throws InterruptedException {

        AtomicBoolean run = new AtomicBoolean(true);
        Random rd = new Random();

        System.out.println("This is the beginning of main thread.");
        new Thread(() -> {
            while (run.get()) {
                int i = rd.nextInt(20);
                System.out.println("i = " + i);
                if (i >= 16) {
                    System.out.println("i >= 16, set run to false.");
                    run.set(false);
                } else {
                    try {
                        System.out.println("Inner thread sleep 1 second.");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("run is set to false already.");
        }).start();
        Thread.sleep(10000);
        run.set(false);
        System.out.println("Main thread sleep for 10 seconds and set run to false.");
    }
    
}
  • If main thread already sleeps for 10 seconds, set run to false, inner thread stops.
  • If inner thread itself set run to false, inner thread stops.

转载于:https://www.jianshu.com/p/177aea9e0c6b