"Java Learning" Multithreading 2

Source: Internet
Author: User

Java Multi-Threading security issues:

Because there may be shared resources in a multithreaded code block, when a thread is using a shared resource, the CPU causes the threads to be hoisted and instead executes another thread, and the second thread uses the shared resource, causing an error to occur when the shared resource is inconsistent.

Java provides a solution for synchronizing blocks of code, which is a good solution to this problem.

Synchronized (object)

{

Accessing shared resource Codes

}

The parameter object can make any object, acting like a switch, when the current thread executes into a synchronous code block, it will first determine the state of the object, if the synchronization code block is not executed by a thread, into the code block, and also set the object's flag bit, to synchronize the code block execution is complete, Set the object's flag bit again to end execution. If a block of code is executed by a thread, the execution of the CPU is discarded directly. An object acts like a lock.

Disadvantages of synchronizing code block schemes:

Multiple threads need to determine the lock and consume more resources.

"Java Learning" Multithreading 2

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.