美文网首页Java
Stop a thread inside & outsi

Stop a thread inside & outsi

作者: JaedenKil | 来源:发表于2019-05-06 16:26 被阅读0次
    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.

    相关文章

      网友评论

        本文标题:Stop a thread inside & outsi

        本文链接:https://www.haomeiwen.com/subject/hmldoqtx.html