Dark Horse Programmer-Multi-Threading (ii)

Source: Internet
Author: User

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

Multi-threaded security issues

Cause: When when multiple statements are working on the same thread to share data, one thread executes only a portion of the multiple statements, has not finished executing, and another thread participates, resulting in a shared data error.

WORKAROUND: Statements that share data on multiple operations can only have one thread complete, and other threads cannot participate in execution during execution. The practice is to use synchronous code blocks:

Synchronized (object) {

Code that needs to be synchronized;


An object is like a lock, a thread that holds a lock can execute in synchronization, and a thread that does not have a lock will not get in even if it gets the execution of the CPU because there is no lock!

Prerequisites for synchronization:

1. There must be two or more threads of two

2. Must be multiple threads using the same lock

3. You must ensure that only one thread is in sync

Benefits: resolves multi-threaded security issues

Disadvantages: Multi-threaded to determine the lock, need to consume resources, slow running efficiency

The lock used by the synchronization function is this, and the lock used by the static synchronization function is the byte code of the current class, that is: class name.

Simple interest design mode for lazy loading:

Class singleton{

private static Singleton single = NULL;

Private Singleton () {}

public static Singleton getinstance () {

if (s==null) {

Synchronized (SINGELTON.CALSS) {

if (s==null) {

s = new Singleton ();

return s;






Dark Horse Programmer-Multi-Threading (ii)

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.