volatile关键字的作用是,在a线程修改变量值后,b线程查看变量的值是修改后的

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

这个例子说的是,启动一个守护线程去处理一个很耗时操作,

设置一个值,超时就结束这个守护线程,当然jvm中要没有其他的用户进程的前提下。

 

public class ThreadService {

    private Thread executeThread;

    private  volatile  boolean  finished = false;

    public void execute(Runnable task) {
        executeThread = new Thread(){
            @Override
            public void run(){
                Thread  runner = new Thread(task);
                runner.setDaemon(true);
                runner.start();
                
                try {
                    runner.join();
                    finished = true;
                } catch (InterruptedException e) {
                }
            }
        };

        executeThread.start();
    }

    public void shutdown(long mills) {
        long currentTime = System.currentTimeMillis();
        while (!finished) {
            if ((System.currentTimeMillis() - currentTime) >= mills) {
                System.out.println("任务超时,需要结束他!");
                executeThread.interrupt();
                break;
            }
        }
    }
}

 

public class ThreadCloseForce {


    public static void main(String[] args) {

        ThreadService service = new ThreadService();
        long start = System.currentTimeMillis();
        service.execute(() -> {
            //load a very heavy resource.
//            while (true) {
//
//            }
            
            try {
                for(int i = 1 ;i <= 5;i++) {
                    System.out.println(" index = "+ i);
                    Thread.sleep(1000);
                }
           
            } catch (InterruptedException e) {
                e.printStackTrace();
           }
        });
        
        service.shutdown(10000);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄