volatile关键字修饰的成员变量,可以告诉虚拟机该成员变量在运行时可能被多个线程多次修改,可是虚拟机每次执行修改调用操作时先进行确认,避免了同步需求,减少系统开销,例子如下:- public class VolatileDemo implements Runnable {
-
- private volatile int number = 0;// 创建一个int类型变量进行测试
-
- @Override
- public void run() {
- for (int i = 0; i < 5; i++) {
- try {
- Thread.sleep(100);// 线程休眠0.1秒增加出错几率
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 输出当前线程的名称和number的值,每次循环之后number的值都会加一
- System.out.println(Thread.currentThread().getName() + ": "
- + number++);
- }
- }
-
- public static void main(String[] args) {
- VolatileDemo run = new VolatileDemo();// 获得SynchronizedMethodDemo对象
- Thread thread1 = new Thread(run);// 创建线程1
- Thread thread2 = new Thread(run);// 创建线程2
- thread1.start();// 运行线程1
- thread2.start();// 运行线程2
- }
- }
复制代码 运行结果:
Thread-0: 0
Thread-1: 1
Thread-0: 2
Thread-1: 3
Thread-0: 4
Thread-1: 5
Thread-0: 6
Thread-1: 7
Thread-0: 8
Thread-1: 9
和加了 synchronized 同步块效果一样,但大大减少系统开销
|