Java

Stop a thread inside & outsi

2019-05-06  本文已影响0人  JaedenKil
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.");
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读