Java thread (25): new feature-atomic weight

Source: Internet
Author: User

Java thread: the new feature-the so-called atomic weight indicates that the operation of the Operation variable is "Atomic". This operation cannot be further divided, so it is thread-safe. Why should we use atomic variables? The reason is that operations on a single variable by multiple threads may also cause some problems. Before Java 5, you can use the volatile and synchronized keywords to solve the security problem of concurrent access, but this is too troublesome. After java 5, java. util. concurrent. atomic is a toolkit dedicated to the concurrent and secure access of single variables and multithreading. The class is also very simple. The following is a negative example (do not imitate): import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. atomic. atomicLong;/*** Java thread: new feature-atomic weight ** @ author leizhimin 2009-11-6 9:53:11 */public class Test {public static void main (String [] args) {ExecutorService pool = Executors. newFixedThreadPool (2); Runnable t1 = new MyRunnable ("Zhang San", 2000); Runnable t2 = new MyRunnable ("Li Si", 3600); Runnable t3 = new MyRunnable ("Wang Wu", 2700); Runnable t4 = new MyRunnable ("Lao Zhang", 600 ); runnable t5 = new MyRunnable ("", 1300); Runnable t6 = new MyRunnable ("", 800); // execute various threads pool.exe cute (t1 ); pool.exe cute (t2); pool.exe cute (t3); pool.exe cute (t4); pool.exe cute (t5); pool.exe cute (t6); // close the thread pool. shutdown () ;}} class MyRunnable implements Runnable {private static AtomicLong Ron G = new AtomicLong (10000); // atomic weight, each thread can operate private String name freely; // operator private int x; // operation amount MyRunnable (String name, int x) {this. name = name; this. x = x;} public void run () {System. out. println (name + "executed" + x + ", current balance:" + aLong. addAndGet (x) ;}} running result: Li Si executed 3600, current balance: 13600 Wang Wu executed 2700, current balance: 16300 Old Zhang executed 600, current balance: 16900 old ox executed 1300, current balance: 18200 fat man executed 800, current balance: 19000 three executed 2000, current balance: 21000 Process finished w Ith exit code 0 Zhang San executed 2000, current balance: 12000 Wang Wu executed 2700, current balance: 18300 Old Zhang executed 600, current balance: 18900 old ox executed 1300, current balance: 20200 fat man executed 800, current balance: 21000 Li Si executed 3600, current balance: 15600 Process finished with exit code 0 Zhang San executed 2000, current balance: 12000 Li Si executed 3600, current Balance: 15600 Old Zhang executed 600, current balance: 18900 old ox executed 1300, current balance: 20200 Fat executed 800, current balance: 21000 Wang Wu executed 2700, current balance: 18300 Process finished with exit code 0 from the running results, we can see that although the atomic weight is used, there is still a problem with concurrent access to the program. What is the problem? Note that although the atomic weight can ensure the security of a single variable in an operation process, it cannot guarantee the security of your entire code block or the entire program. Therefore, synchronization mechanisms such as locks should also be used to control the security of the entire program. The following is an error correction: import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; import java. util. concurrent. atomic. atomicLong;/*** Java thread: new feature-atomic weight ** @ author leizhimin 2009-11-6 9:53:11 */public class Test {public static void main (String [] args) {ExecutorService pool = Executors. newFixedThr EadPool (2); Lock lock = new ReentrantLock (false); Runnable t1 = new MyRunnable ("Zhang San", 2000, lock); Runnable t2 = new MyRunnable ("Li Si ", 3600, lock); Runnable t3 = new MyRunnable ("Wang Wu", 2700, lock); Runnable t4 = new MyRunnable ("Lao Zhang", 600, lock ); runnable t5 = new MyRunnable ("old ox", 1300, lock); Runnable t6 = new MyRunnable ("Fat Man", 800, lock ); // execute each thread pool.exe cute (t1); pool.exe cute (t2); pool.exe cute (t3 ); Pool.exe cute (t4); pool.exe cute (t5); pool.exe cute (t6); // close the thread pool. shutdown () ;}} class MyRunnable implements Runnable {private static AtomicLong aLong = new AtomicLong (10000); // atomic weight, each thread can operate private String name freely; // operator private int x; // operation amount private Lock lock; MyRunnable (String name, int x, Lock lock) {this. name = name; this. x = x; this. lock = lock;} public void run () {lock. lock (); System. ou T. println (name + "executed" + x + ", current balance:" + aLong. addAndGet (x); lock. unlock () ;}} execution result: Michael performed 2000, the current balance was 12000, the current balance was 2700, the current balance was 14700, and the current balance was 600: 15300 the old ox executes 1300, the current balance is 16600, the current balance is 800, the current balance is 17400, and the current balance is: 21000 Process finished with exit code 0 an object lock is used here to control access to concurrent code. The final balance is 21000 no matter how many runs and the execution order. This result is correct. The usage of atomic weights is very simple. The key is to understand atomic weights. atoms only ensure the atomicity of variable operations, but thread security needs to be considered in the whole program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.