Java multi-thread synchronized

Source: Internet
Author: User

Java multi-thread synchronized

First, let's look at the next scenario. A cinema sells tickets for four windows at a time. There are only 100 tickets in total for this movie. Check the actual code.

 

Package cn.com. thread; public class TestThread {public static void main (String [] args) {SellTicketThread t = new SellTicketThread (); new Thread (t, window 1 ). start (); new Thread (t, window 2 ). start (); new Thread (t, window 3 ). start (); new Thread (t, Window 4 ). start ();}}
package cn.com.thread;public class SellTicketThread extends Thread {private int ticket = 100;@Overridepublic void run() {while (true) {if(sellTicket()){break;}}}private boolean sellTicket() {try {if (ticket <= 0) {return true;}Thread.sleep(30);} catch (Exception e) {}System.out.println(Thread.currentThread().getName()+:+(ticket--));return false;}}

According to the running results, a negative number is found. It is not feasible in actual business.

Thus, we come to the following conclusion:When multiple threads access instance variables in an object, 'non-thread security' may occur '.

 

Synchronized Method

 

If you add the keyword synchronized to the method, the above problem will not occur.

 

package cn.com.thread;public class SellTicketThread extends Thread {private int ticket = 100;@Overridepublic void run() {while (true) {if(sellTicket()){break;}}}private synchronized boolean sellTicket() {try {if (ticket <= 0) {return true;}Thread.sleep(30);} catch (Exception e) {}System.out.println(Thread.currentThread().getName()+:+(ticket--));return false;}}

 

Some people have to ask, since the lock is applied, our code can only be called by one thread, which does not reduce the efficiency, why is there no multi-thread concurrency in the synchronization code? If you can think of this, it means you know about the lock mechanism. Indeed, the situation is true, because we should try to narrow down the scope of the synchronization lock. Is there any principle? Therefore, the time synchronization method is not suitable.

 

Synchronized code block

 

If we want to do the relevant work before selling tickets. For example, if we bought a ticket in Meituan, we may need to verify whether you bought the ticket in Meituan and decide whether to issue the ticket. This process is quite time-consuming, and everyone is accessing it with a separate object, so it is thread-safe, but it is not suitable if we use the synchronized method.

 

Package cn.com. thread; public class SellTicketThread extends Thread {private int ticket = 100; private Object lock = new Object (); @ Overridepublic void run () {while (true) {if (sellTicket () {break ;}} private boolean sellTicket () {System. out. println (validation logic, which takes 10 seconds); try {synchronized (lock) {if (ticket <= 0) {return true;} System. out. println (Thread. currentThread (). getName () +: + (ticket --);} Thread. sleep (30);} catch (Exception e) {} return false ;}}

From the above example, we can see that this is also the result we want. So how can we define a lock?

 

The so-called lock is to prevent multiple threads from simultaneously operating a copy of data. If the data operated by multiple threads are independent, there is no need to lock the data.
The lock of shared data must be the same for the threads accessing them. Otherwise, the lock can only be private. Each lock cannot protect the shared data, imagine putting the definition of Object lock in the run method, and a lock will be instantiated each time. The Locks obtained by each thread are different, so there is no competition, in other words, there is A lock on the door of building A, and A wants to enter the door. There is A lock on the door of Building B wants to enter the door. A and B are not robbing the door, therefore, data protection or sharing does not exist;
The definition of a lock can be any object. This object can be unique as long as it does not participate in any operation;

 

 

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.