The atomicity of multithreading concurrency (vi)

Source: Internet
Author: User

Recently found on the internet a lot of multi-threaded examples of atomicity, said is not very clear, for the novice learning multithreading is very misleading students, here, I have a number of examples of multi-threaded atom to illustrate.

Example one: traditional technology self-increment
Package Face.thread.volatilep;public class Counter2 {    private  int count = 0;     Public synchronized Void Inc () {        count = count + 1;    }     public static void Main (string[] args) {         //start 1000 threads at the same time, go to the i++ calculation and see the actual result    final Counter2 C = new Counter2 ();            for (int i = 0; i < i++) {            new Thread (new Runnable () {@Override public                void Run () {                c.inc (); c13/>}            }). Start ();        }                try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();}        There may be different values for each run, which may be        System.out.println ("Run Result: counter.count=" + C.count);}    }


The result of the above code is occasionally equal to 1000, there are basically some errors, because the order of thread execution is not guaranteed, it is likely that the new 1000 threads have not finished, our code

  SYSTEM.OUT.PRINTLN ("Running result: counter.count=" + counter.count);

has been executed, to solve this problem is very simple, that is, the last sentence println before the thread sleep for a period of time, such as sleep 2 seconds. Wait for 1000 threads to finish executing, in print "

"Operation Result: counter.count=" + Counter.count ";

It can also be solved with the help of a thread-assisted class, where the simplest example is shown here:

Package Face.thread.volatilep;import Java.util.concurrent.brokenbarrierexception;import Java.util.concurrent.cyclicbarrier;public class Counter3 {      int count =0;      Public Synchronized  Void Inc () {    count++;    }     public static void Main (string[] args) {         //start 1000 threads at the same time, go to the i++ calculation and see the actual result    final Counter3 C = new Counter3 ();           Final cyclicbarrier cy = new Cyclicbarrier (10000, new Runnable () {public  void run () {          //The value of each run here may be different, possibly 1000 C11/>SYSTEM.OUT.PRINTLN ("Run Result: counter.count=" + c.count);  }  );              for (int i = 0; i < 10000; i++) {            new Thread (new Runnable () {                @Override public                void Run () {                c.inc () ;                try {cy.await ();} catch (Interruptedexception e) {e.printstacktrace ()} catch (Brokenbarrierexception e) { E.printstacktrace ();}                }            ). Start ();}}            }


Example two: the Atomic self-increment atom is the smallest unit in the world and is indivisible. such as A=0; (a non-long and double type) This operation is indivisible, then we say this operation is atomic operation. Another example: a++; This operation is actually a = a + 1; is divisible, so he is not an atomic operation. There is a thread-safety problem with non-atomic operations, and we need to use synchronous technology (sychronized) to turn it into an atomic operation. An operation is an atomic operation, so we call it atomic. The Java concurrent package provides some atomic classes, and we can read the API to understand the use of these atomic classes. For example: Atomicinteger, Atomiclong, atomicreference and so on. Because atomicity is thread-safe, there is no need for a traditional lock-up technique for atomic self-amplification, depending on the code:
Package Face.thread.volatilep;import Java.util.concurrent.atomic.atomicinteger;public Class CounterNew2{ Atomicinteger count = new Atomicinteger (0);p ublic void increment () {count.getandincrement ();} public int GetCount () {return count.get ();} public static void Main (string[] args) {final CounterNew2 cn = new CounterNew2 (); for (int i = 0; i < 10000;i++) {new THR EAD (New Runnable () {public void run () {cn.increment ();}}). Start ();} try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Count Final return Value:" + cn.getcount ());}}
The running result is also: 10000

The atomicity of multithreading concurrency (vi)

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.