Java Multithreading (four)

Source: Internet
Author: User

1. Prerequisites for synchronization

Multiple threads

Multiple threads are using the same lock

2. Benefits of synchronization

The advent of synchronization solves the security problem of multithreading

3. Disadvantages of synchronization

When the thread is more, because each thread will judge the lock on the synchronization, this is very resource-intensive, it will reduce the efficiency of the program running.

4. Synchronization method:

1. Is the synchronization of the keyword, synchronized added to the method, the lock object is this

2. The lock object of the static method is the bytecode file object of the class, Xxx.class

Lock locks after 5.jdk5

Two methods of the lock interface

Lock (): Get lock

Unlock (): Release lock

Sub-class: Reentrantlock ()

By calling these two methods of the subclass, acquiring the lock, releasing the lock, and wrapping the code block that needs to be synchronized, you can also solve the thread safety problem. The following pseudocode:

    Reentrantlock lock= new Reentrantlock ();

try{

Lock.lock ();

Synchronization code;

}finally{

Lock.unlock ();

}

6. Synchronization drawbacks

A. Low efficiency

B. If there is a synchronous nesting, it is easy to create a deadlock

    Deadlock: Two or more threads, which are waiting for each other in the process of competing for resources.

7. Inter-thread communication

Different kinds of threads operate on the same resource. (Producer, consumer)

Producers, consumers, waiting for the wake-up mechanism:

  

Java Multithreading (four)

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.