In Java parallel programming, the volatile keyword ensures consistent access to shared variables in a multi-threaded environment: declaring variables volatile to prevent the processor from reordering optimizations. Ensure that all threads access shared variables in a consistent manner to prevent inconsistency. The sample code demonstrates the use of the volatile keyword to correctly calculate counters in a multi-threaded environment.
The role and usage of the volatile keyword in Java parallel programming
Introduction
volatile
The keyword is very important in Java parallel programming. It is used to ensure correct access to shared variables in a multi-threaded environment. It does this by preventing the processor from performing reordering optimizations on shared variables.
Function
volatile
The keyword has the following functions:
Syntax
volatile
Keywords can be applied to instance variables and local variables:
//实例变量 private volatile int counter; //局部变量 public void incrementCounter() { volatile int count = counter; ... }
Reordering optimization
In order to improve performance, processors often perform reordering optimization on instructions. However, in a multi-threaded environment, this can lead to inconsistencies in thread access to shared variables.
Consider the following code:
public class Counter { private int counter; public void incrementCounter() { counter++; } public int getCounter() { return counter; } }
If the volatile
keyword is not used, the processor may react to the incrementCounter()
method and getCounter ()
The instructions in the method are reordered, resulting in the read counter
value being not the latest.
Practical case
The following is an example of using the volatile
keyword to ensure that the counter works correctly in a multi-threaded environment:
public class VolatileCounterDemo { private volatile int counter; public void incrementCounter() { counter++; } public static void main(String[] args) throws InterruptedException { VolatileCounterDemo demo = new VolatileCounterDemo(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000000; i++) { demo.incrementCounter(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000000; i++) { demo.incrementCounter(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("最终计数器值:" + demo.counter); } }
Output:
最终计数器值:2000000
The above is the detailed content of The role and usage of volatile keyword in Java parallel programming. For more information, please follow other related articles on the PHP Chinese website!