Java Learning notes Multi-Threading Two

Source: Internet
Author: User
Tags ticket

See a thread-telling story, it is very interesting, I admire the author can be so vivid to tell, click to jump to read this article: "I am a thread"

  

Continue to summarize in my notes--

Understanding Thread safety issues:

Here are the examples of the tickets you see in the book: Simulate 3 windows and sell 10 tickets at the same time.

The last blog note summarizes the two ways to create multithreading, and then we will solve this scenario in two different ways.

    • Using the method inherited from the thread class

On Demo:

classSaleticketextendsThread {intnum = 10;//Number of votes         PublicSaleticket (String name) {Super(name); } @Override Public voidrun () { while(true) {            if(num > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "window sold" + num + "Ticket" ); Try{sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } num--; } Else{System.out.println ("It's sold out ...");  Break; }        }    }} Public classDemo1 { Public Static voidMain (string[] args) {//Create three thread objectsSaleticket Th1 =NewSaleticket ("A"); Saleticket Th2=NewSaleticket ("B"); Saleticket Th3=NewSaleticket ("C"); //Open ThreadTh1.start ();        Th2.start ();    Th3.start (); }}

Dmeo1 execution result diagram is:

  

From the experimental results, the original 10 tickets sold 30, why?

Originally, this is because: the number of votes num is declared for a non-static member variable, but not a static member variable that maintains one copy of the data in each object. Then there are three num variables created for three thread objects-that is, we want to make the votes num share one copy for three threads, so we need to set the number num variable to static member variable. That
Static int num = 10; // votes  are non-static member variables, and non-static member variable data is maintained for each object in one piece of data. 

After the change is completed, the results are as follows:

    

At this time, it is found that the output is 10 records (except the first three may be wrong three), indicating that static function, to achieve the purpose of sharing.

But a careful look, the new problem with it, A, B, c window actually will appear to sell the same ticket situation! Why?

This has hooked up to today's topic, thread-safety issues.

The analysis is as follows:

Assume that the a thread first robs the CPU of execution, starts execution when it executes to

System.out.println (Thread.CurrentThread (). GetName () + "window sold" + num + "ticket");

After (num--is not executed), NUM is 10, at which point the B thread preempted the CPU execution to begin execution, and the same execution to

System.out.println (Thread.CurrentThread (). GetName () + "window sold" + num + "ticket");

, num grabs the CPU execution for the 50,C thread, and C executes to the same code as the AB execution, where the ABC three NUM values are 10;

Consider, then, how to ensure that when a thread executes the entire block of code, it is not disturbed by other threads?

Thus, Java provides a synchronization mechanism to address thread safety issues.

Synchronization mechanism is divided into synchronous code block and synchronous method

First look at the format of the synchronized code block:

synchronized (Lock object) {    // code that needs to be synchronized ...     }

When a thread wants to use a train ticket for this resource, we give it a lock, and then lock it to another thread that needs to use the resource when it's done.

In this case, the code that is analyzed above that is likely to cause thread safety issues is placed in the Synchronized code block:
 synchronized  (Saleticket.  if  (num > 0 + "window sold the" + num + "ticket"  );  try   {sleep ( 100);  catch   (Interruptedexception e) {e.        Printstacktrace ();    Num --;  else   {System.out.println ( "Sales        Exhausted ... ");     break  ; }}

Run it again:

    

This leads us to the right results.

Things to keep in mind when synchronizing code blocks:

    1. The lock object can be an arbitrary object. 2. A thread sleep in a synchronized code block and does not release the lock object. 3. The lock object must be a resource for multi-threaded sharing, otherwise it cannot be locked.     4. If there is no thread-safety problem, do not use the synchronous code block, because it will reduce efficiency. Synchronous code blocks can also be implemented using synchronous methods: The synchronization method puts code that is likely to have thread safety issues in a function that is implemented as follows:
 Public voidrun () { while(true) {        if(num > 0) {            Try{sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }             This. Sale (); } Else {             Break; }                }}
Synchronization Method Public synchronized voidSale () {if(num > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "window sold" + (num--) + "Ticket" ); }}

Things to note about synchronization functions:

1. If the lock object that is a non-static synchronization function is the This object, the lock object of the static synchronization function is the bytecode file (class object) of the class to which the current function belongs. 2. The lock object of the synchronization function is fixed and cannot be arbitrarily specified.

  So, for the two ways to implement the synchronization mechanism, it is recommended to use: Synchronous code block

The reason is also simple:

1. The lock object of the synchronization code block can be specified by us at will, which is convenient to control.    The lock object of the synchronous method is fixed. 2. Synchronizing code blocks makes it easy to control the range of code that needs to be synchronized, and the synchronization function must be all the code for the entire function to be synchronized.
    • How to implement the Runnable interface using:

Demo2:

classSaleTicket2ImplementsRunnable {intnum = 10; @Override Public voidrun () { while(true) {            synchronized(SaleTicket2.class) {                if(num > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "window sold" + num + "Ticket"); Num--; } Else {                     Break; }                            }        }    }}
Public classDemo2 { Public Static voidMain (string[] args) {//An object that creates a Runnable implementation classSaleTicket2 Saleticket =NewSaleTicket2 (); //create three thread objects to simulate three windowsThread Th1 =NewThread (Saleticket, "A"); Thread Th2=NewThread (Saleticket, "B"); Thread Th3=NewThread (Saleticket, "C"); //turn on thread ticketingTh1.start (); Th2.start (); Th3.start (); }}

Operation, the results are as follows:

Also got the right result.

Summarize:

What are the root causes of thread safety issues?

1. There are two or more thread objects, and the same resource is shared between threads.

2. There are multiple statements that operate on shared resources.

Solution:

Use the synchronization mechanism to resolve code snippets that could cause thread safety problems by synchronizing code blocks (recommended) or synchronous methods.

Java Learning notes Multi-Threading Two

Related Article

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.