volatile关键字(有什么用?)

196 阅读1分钟

一句话:线程间的共享变量使用volatile修饰后会立即生效!

特性:可见性
一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。
线程间的共享变量需要用Volatile修饰,保证一个线程修改共享变量后对其他线程是立即可见的。
未使用volatile修饰
48.750
49.589
差:161
使用volatile
31.162
31.135
差:27
使用interrupt方法中断
38.400
39.177
差:223

class TestThread extends Thread{
    public volatile boolean isInterrupted=true;

    @Override
    public void run() {

        while (isInterrupted){
            System.out.println("11");
            Log.e("wy", "run: ");
        }

//        使用中断方法interrupt进行线程中断
//        while (!isInterrupted()){
//            System.out.println("11");
//            Log.e("wy", "run: ");
//        }
    }
}
 
 TestThread mTestThread=new TestThread();
        mTestThread .start();
        try {
            Thread.sleep(1000);
            mTestThread.isInterrupted=false;
//            mTestThread.interrupt();
        } catch (InterruptedException mE) {
            mE.printStackTrace();
        }