synchronized是阻塞式同步,在线程竞争激烈的情况下会升级为重量级锁。而volatile可以说是java虚拟机提供的最轻量级的同步机制。
根据Java内存模型,各个线程会将共享变量从主内存中拷贝到工作内存,然后执行引擎会基于工作内存中的数据进行操作处理。线程在工作内存进行操作后何时写到主内存是不确定的。volatile修饰的变量给java虚拟机特殊的约定,线程对volatile变量的修改会立刻被其他线程所感知,不会出现数据脏读的现象,从而保证数据的“可见性”。被volatile修饰的变量确保每个线程能够获取该变量的最新值。
package com.bjsxt.base.sync007; public class RunThread extends Thread{ private volatile boolean isRunning = true; private void setRunning(boolean isRunning){ this.isRunning = isRunning; } public void run(){ System.out.println("进入run方法.."+Thread.currentThread().getName()); int i = 0; while(isRunning == true){ //.. // System.out.println("线程是否开启:"+isRunning); } System.out.println("线程停止.."+Thread.currentThread().getName()); } public static void main(String[] args) throws InterruptedException { RunThread rt = new RunThread(); rt.start(); Thread.sleep(10); rt.setRunning(false); System.out.println("isRunning的值已经被设置了false.."+Thread.currentThread().getName()); } }
打印
进入run方法..Thread-0
isRunning的值已经被设置了false..main
线程停止..Thread-0
package com.bjsxt.base.conn008; import java.util.ArrayList; import java.util.List; public class ListAdd1 { private volatile static List list = new ArrayList(); public void add(){ list.add("bjsxt"); } public int size(){ return list.size(); } public static void main(String[] args) { final ListAdd1 list1 = new ListAdd1(); Thread t1 = new Thread(new Runnable() { @Override public void run() { try { for(int i = 0; i <10; i++){ list1.add(); System.out.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素.."); Thread.sleep(500); } } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { while(true){ if(list1.size() == 5){ System.out.println("当前线程收到通知:" + Thread.currentThread().getName() + " list size = 5 线程停止.."); throw new RuntimeException(); } } } }, "t2"); t1.start(); t2.start(); } }
原文:https://www.cnblogs.com/hongyedeboke/p/13332898.html