Javase Multi-Threading (iv)

Source: Internet
Author: User
Tags thread class ticket

Today is still multi-threading, but before doing a practice, with multi-threaded mock cinema ticket sales, the problem: A movie theater is currently on the release of the Lunar New Day blockbuster (Red Sorghum, Shaolin Temple legend Sutra Pavilion), a total of 100 tickets, and it has 3 ticket window ticket, please design a program to simulate the cinema ticket sales.

We know that there are two ways to implement threading, let's take a look at the first way: inheriting the thread class implementation. the specific code is as follows:

 Public classSellticketextendsThread {//Define 100 Tickets//private int tickets=100; //in order for multiple thread objects to share these 100 tickets, we should actually use static retouching    Private Static inttickets=100;  PublicSellticket () {Super(); }         PublicSellticket (String name) {Super(name); } @Override Public voidrun () {//each thread comes in and goes here, so that each thread object is equivalent to buying the 100 tickets of its own, which is unreasonable, so it should be defined outside//int tickets=100;//Define 100 Tickets//Analog Cinema has always had tickets for sale         while(true){        if(tickets>0) {System.out.println (GetName ()+ "Selling" + (tickets--) + "Ticket"); }        }    }}/** Method 1: Inherit the thread class to implement. */ Public classSellticketdemo { Public Static voidMain (string[] args) {//Create three thread objectsSellticket st1=NewSellticket ("Windows 1"); Sellticket St2=NewSellticket ("Windows 2"); Sellticket ST3=NewSellticket ("Windows 3"); //Start ThreadSt1.start ();        St2.start ();    St3.start (); }}

Mode one run Result:

Through the analysis of the code, found reasonable, the votes of the tickets declared as static let three thread objects to share, can run the results on the show, the last ticket unexpectedly sold two times the problem. So this is a problem, and later on, this is the second way to implement it: implement the Runnable interface. the code is as follows:

 Public classSellticketImplementsRunnable {//Define 100 Tickets    Private inttickets=100; @Override Public voidrun () {//Analog Cinema has always had tickets for sale         while(true) {            if(Tickets > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Selling" + (tickets--) + "Ticket"); }        }    }}/*** * Mode two: Implement Runnable interface Create thread **/ Public classSellticketdemo { Public Static voidMain (string[] args) {//Create a Resource objectSellticket st =NewSellticket (); //Create three thread objectsThread t1=NewThread (St, "Window 1")); Thread T2=NewThread (St, "Window 2")); Thread T3=NewThread (St, "Window 3")); //Start ThreadT1.start ();        T2.start ();            T3.start (); }}

Mode two run Result:

Before saying the difference between the two ways, it is clear to find that the second way is relatively good, strongly recommended to use. Mode two just create a resource object, that is 100 tickets, will not appear the same ticket has been sold many times of the wonderful situation.

The above code, in fact, does not fully simulate the ticket sales, because the network at the time of the ticket to the appropriate delay, the following improvements in the next mode of the code to simulate the situation of network latency. The improved code is as follows:

 Public classSellticketImplementsRunnable {//Define 100 Tickets    Private inttickets=100; @Override Public voidrun () {//Analog Cinema has always had tickets for sale         while(true) {            if(Tickets > 0) {                //To simulate a more realistic scenario, you need to add a delay                Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Selling" + (tickets--) + "Ticket"); }        }    }}/*** * Improved Mode II: Implement RUNNABLE interface Create thread **/ Public classSellticketdemo { Public Static voidMain (string[] args) {//Create a Resource objectSellticket st =NewSellticket (); //Create three thread objectsThread t1=NewThread (St, "Window 1")); Thread T2=NewThread (St, "Window 2")); Thread T3=NewThread (St, "Window 3")); //Start ThreadT1.start ();        T2.start ();            T3.start (); }}

Improved running results:

Through the analysis of the improved running results, we found two questions: A: The same ticket sold many times; B: There was a negative vote.

First of all, why the same ticket appears, because the CPU operation must be atomic (Atomicity refers to the simplest and most basic operation, can not be subdivided operations). The analysis is as follows:

In the ideal state, when the thread T1 run up to sleep when the rest, at this time the thread t2 the execution of the CPU, also ran to sleep began to rest, at this time T1 and began to run, print out "is selling the 100th ticket", after doing the self-reduction operation, T2 also after the rest of the start run, will print " Is selling the 99th ticket ", but the actual situation is often different, is that it will appear when T1 print" is selling the 100th ticket "has not yet time to do the self-reduction operation, T2 again run up, so will print the same ticket, that is the same ticket sold several times.

Say why there is a negative vote, which is due to randomness and delay. The analysis is as follows:

Due to randomness, there may be three threads in the ticket number for the last time to enter the sleep in the while loop, and all rest, and then, T1 after printing, T2 after printing, T3 after printing self-reduction, that is to say:

Window 1 is selling the 1th ticket, tickets=0.
Window 2 is selling the No. 0 ticket, Tickets=-1.
Window 3 is selling--1 tickets, tickets=-2.

To sum up, there will be a negative vote.

One, thread safety

1. The cause of thread safety problems (also the criteria for determining if a program has a thread safety issue):

A: Whether it is a multithreaded environment
B: Do you have shared data
C: Is there more than one statement to manipulate shared data

In fact, the practice in front of me, is to meet the three conditions, resulting in a thread security problem, then how to solve the problem of thread safety?

2. Ways to troubleshoot thread safety issues:

solve the idea: put multiple statements to manipulate the code of the shared data into a whole, so that a thread at execution time, others can not be executed (Java synchronization Mechanism).

Solution One : synchronizing code blocks

Format:

synchronized ( object ) {//code that needs to be synchronized; (Multiple statement operations share the code portion of the data)}

Attention:

1. Synchronous code blocks the root cause of the thread-safety problem is the object, which is like a lock that locks other non-running lines outside the door.

2. Multiple threads must be the same lock

Here's the code to resolve thread-safety issues by synchronizing code blocks:

 Public classSellticketImplementsRunnable {//Define 100 Tickets    Private inttickets=100; //To Create a lock object    Private Object obj=new Object (); @Override Public voidrun () {//Analog Cinema has always had tickets for sale         while(true) {            synchronized (obj) {if(Tickets > 0) {                    //To simulate a more realistic scenario, you need to add a delay                    Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Selling" + (tickets--) + "Ticket"); }            }                    }    }}/*** * Synchronize code blocks to resolve thread safety issues **/ Public classSellticketdemo { Public Static voidMain (string[] args) {//Create a Resource objectSellticket st =NewSellticket (); //Create three thread objectsThread t1=NewThread (St, "Window 1")); Thread T2=NewThread (St, "Window 2")); Thread T3=NewThread (St, "Window 3")); //Start ThreadT1.start ();        T2.start ();            T3.start (); }}

Explanation of the synchronous code block: For example, this figure is drawn by myself, not particularly good, when I can explain it slightly.

Summarize the following points about synchronization:

Features of synchronization:
premise: Multiple threads
when solving the problem, be aware that multiple threads are using the same lock object
Benefits of Synchronization : The advent of synchronization solves the security problem of multithreading.
The disadvantage of synchronization : When the thread is quite a long time, because each thread will judge the synchronization of the lock, this is very resource-intensive, virtually reduce the program's operational efficiency.
The article ends here.

Javase Multi-Threading (iv)

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.