Threading issues--synchronization and deadlock

Source: Internet
Author: User

"Problem arises": For example, for the ticket system, there is the following code:

1 classHelloImplementsRunnable {2     Private Static intCount=5;3      Public voidrun () {4          for(inti=0;i<10;++i) {5             if(count>0){6                 Try{7Thread.Sleep (1000);8}Catch(interruptedexception e) {9 e.printstacktrace ();Ten                 } OneSystem.out.println (count--); A             } -         } -     } the   -      Public Static voidMain (string[] args) { -Hello he=Newhello (); -Thread h1=NewThread (He); +Thread h2=NewThread (He); -Thread h3=NewThread (He); + H1.start (); A H2.start (); at H3.start (); -     } -}

"Run Results"

5
4
3
2
1
0
-1

Here comes the-1, obviously this is wrong. , the number of votes should not be negative.

If you want to solve this problem, you need to use synchronization. The so-called synchronization is that only one thread runs in the unified time period,

The other thread must wait until the thread finishes before it can continue execution.

"Use thread synchronization to resolve issues"

With synchronization, you can use Synchronous code block and synchronization method of two kinds to complete.

(i) Synchronizing code blocks

Syntax format:

Synchronized (synchronization object) {

Code that needs to be synchronized

}

However, the current object this is generally used as the synchronization object.

For example, the question of buying tickets above is as follows (Modify the Run method):

 Public voidrun () { for(inti=0;i<10;++i) {            synchronized( This){                if(count>0){                    Try{Thread.Sleep (1000); }Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Count--); }            }        }    }

"Run Result": (output one result per second)

5

4

3

2

1

(ii) Synchronization method

The syntax format is

Synchronized method return type method name (parameter list) {

Other code

}

Modify the Run method

 Public voidrun () { for(inti = 0; I < 10; ++i) {sale (); }    }      Public synchronized voidSale () {if(Count > 0) {            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Count--); }    }

The results of the operation are as above.

As a reminder, synchronization is required when multiple threads share a resource, but excessive synchronization can lead to deadlocks .

Threading issues--synchronization and deadlock

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.