黄金路网站建设公司,网站开发者id,做微网站的第三方,网站设计模板照片Java多线程常用的几个关键字二、volatile作用#xff1a;volatile关键字的作用是#xff1a;使变量在多个线程间可见(具有可见性)#xff0c;但是仅靠volatile是不能保证线程的安全性#xff0c;volatile关键字不具备synchronized关键字的原子性。Demo1:package com.ietree…Java多线程常用的几个关键字二、volatile作用volatile关键字的作用是使变量在多个线程间可见(具有可见性)但是仅靠volatile是不能保证线程的安全性volatile关键字不具备synchronized关键字的原子性。Demo1:package com.ietree.multithread.sync;public class RunThread extends Thread {// volatileprivate boolean isRunning true;private void setRunning(boolean isRunning) {this.isRunning isRunning;}public void run() {System.out.println(进入run方法..);int i 0;while (isRunning true) {// ..}System.out.println(线程停止);}public static void main(String[] args) throws InterruptedException {RunThread rt new RunThread();rt.start();Thread.sleep(1000);rt.setRunning(false);System.out.println(isRunning的值已经被设置了false);}}程序输出进入run方法..isRunning的值已经被设置了false之后进入死循环Demo2package com.ietree.multithread.sync;public class RunThread extends Thread {// volatileprivate volatile boolean isRunning true;private void setRunning(boolean isRunning) {this.isRunning isRunning;}public void run() {System.out.println(进入run方法..);int i 0;while (isRunning true) {// ..}System.out.println(线程停止);}public static void main(String[] args) throws InterruptedException {RunThread rt new RunThread();rt.start();Thread.sleep(1000);rt.setRunning(false);System.out.println(isRunning的值已经被设置了false);}}程序输出isRunning的值已经被设置了false线程停止总结当多个线程之间需要根据某个条件确定 哪个线程可以执行时要确保这个条件在 线程之间是可见的。因此可以用volatile修饰。volatile 与 synchronized 的比较①volatile轻量级只能修饰变量。synchronized重量级还可修饰方法②volatile只能保证数据的可见性不能用来同步因为多个线程并发访问volatile修饰的变量不会阻塞。synchronized不仅保证可见性而且还保证原子性因为只有获得了锁的线程才能进入临界区从而保证临界区中的所有语句都全部执行。多个线程争抢synchronized锁对象时会出现阻塞。线程安全性包括两个方面①可见性。②原子性。从上面自增的例子中可以看出仅仅使用volatile并不能保证线程安全性。而synchronized则可实现线程的安全性。【Java多线程常用的几个关键字】相关文章