The concept of race conditions, locks, and synchronizations in Java Multi-threading

Source: Internet
Author: User

Competitive conditions

1. Competitive Conditions:

In Java Multi-threading, when two or more threads operate on the same data, a "race condition" may occur. The root cause of this behavior is because multiple threads are working on the same data at which point the operation of the data is not "atomized", possibly the previous thread's operation on the data is not over, and the latter thread begins to operate on the same data, which can cause changes in the data results to be unknown.

 Packagecom.huojg.test; Public classTestthread { Public Static voidMain (string[] args) {//New Object TMyThread T =NewMyThread (); /*** Two threads are working on the same object*/Thread ta=NewThread (T, "thread-a"); Thread TB=NewThread (T, "Thread-b");          Ta.start ();      Tb.start (); }  }    classMyThreadImplementsRunnable {//variable A is co-operated by two threads, which can cause a thread to compete    intA = 10; @Override Public voidrun () { for(inti = 0; I < 5; i++) {a-= 1; Try{Thread.Sleep (1); } Catch(Interruptedexception e) {} System.out.println (Thread.CurrentThread (). GetName ()+ "→a =" +a); }      }  }  

The results show:

Thread-a→a = 8thread-b→a = 8thread-a→a = 6thread-b→a = 6thread-b→a = 4Th Read-a→a = 4thread-b→a = 2thread-a→a = 2thread-a→a = 0thread-b→a = 0

As we can see from the above results, after thread A has manipulated the data, he has not had time for the next operation of the data, at which point the data is also manipulated, which results in a one-time reduction of two times, so that the value of a 9 is not printed at all, and a is 0 when it is printed two times.

So, how can we avoid the outcome of this situation?

2. Thread Lock

If one thread is working on the data, it is forbidden to manipulate this data by another thread, then the above problem can be solved well. This operation is called a wire Cheng.

 Packagecom.huojg.test;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;/*** in Java Multi-threading, when two or more threads operate on the same data, a "race condition" may occur. The root cause of this behavior is that multiple threads are working on the same data at which point the operation of the data is not "atomized", * Possibly the previous thread's operation on the data is not over, and the next thread begins to operate on the same data, which can cause changes in the data results to be unknown. * * * 2. Thread lock If another thread is forbidden to manipulate this data while one thread is manipulating the data, the above problem can be solved well. This operation is called a wire Cheng. * */ Public classTestthread { Public Static voidMain (string[] args) {//New Object TMyThread T =NewMyThread (); /*** Two threads are working on the same object*/Thread ta=NewThread (T, "thread-a"); Thread TB=NewThread (T, "Thread-b");          Ta.start ();      Tb.start (); }  }    classMyThreadImplementsRunnable {//declaring Locks    PrivateLock lock =NewReentrantlock (); //variable A is co-operated by two threads, which can cause a thread to compete    intA = 10; @Override Public voidrun () {//LockingLock.lock ();  for(inti = 0; I < 5; i++) {a-= 1; Try{Thread.Sleep (1); } Catch(Interruptedexception e) {} System.out.println (Thread.CurrentThread (). GetName ()+ "→a =" +a);    } lock.unlock (); }  }  

Operation Result:

Thread-a→a = 9thread-a→a = 8thread-a→a = 7thread-a→a = 6thread-a→a = 5Th Read-b→a = 4thread-b→a = 3thread-b→a = 2thread-b→a = 1thread-b→a = 0

The above code gives the way to the thread yoke, you can see that the process of the data before the operation of the operation to add a lock, then when this thread to the data operation, the other threads can not operate on this data, only "blocking" While waiting for the current thread to perform the next operation on the data after the end of the data operation, the current thread will unlock the current lock after the data operation completes so that the next thread can manipulate the data

Lock the method with the Synchronized keyword Gathalai: The result is the same;

Summarize:

Multi-Threading in Java, when multiple threads operate on one data, can create a "race condition" that requires the locking of a thread's operations to solve a problem that can occur when a single data is multithreaded. There are two ways to lock, one is to declare the lock object to quickly lock the statement, the other is to use the Synchronized keyword to lock the method. Both of these methods can effectively solve the problem of competitive conditions in Java Multi-threading.

The concept of race conditions, locks, and synchronizations in Java Multi-threading

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.