Java Concurrency, synchronized locked content

synchronized with what's locked in on approach?

This method is currently locked object, so that other threads may access the synchronized methods of the object or becoming blocked, but will not be blocked and non-synchronized method.

Dirty read

A common concept. In a multithreaded, will inevitably arise in the case of concurrent access of multiple threads of instance variables or static global variables of the same object, if not properly sync, then the consequences arising is the "dirty read", that is, take the data is actually being changed before. Note that local variables is the case that there is no dirty reads

 

public class ThreadDomain13
{
    private int num = 0;
    
    public void addNum(String userName)
    {
        try
        {
            if ("a".equals(userName))
            {
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            }
            else
            {
                num = 200;
                System.out.println("b set over!");
            }
            System.out.println(userName + " num = " + num);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

 

Write two threads to add the string "a" and the string "b", respectively:

 

public class MyThread13_0 extends Thread
{
    private ThreadDomain13 td;
    
    public MyThread13_0(ThreadDomain13 td)
    {
        this.td = td;
    }
    
    public void run()
    {
        td.addNum("a");
    }
}
public class MyThread13_1 extends Thread
{
    private ThreadDomain13 td;
    
    public MyThread13_1(ThreadDomain13 td)
    {
        this.td = td;
    }
    
    public void run()
    {
        td.addNum("b");
    }
}

Write a main function of each running two threads:

public static void main(String[] args)
{
    ThreadDomain13 td = new ThreadDomain13();
    MyThread13_0 mt0 = new MyThread13_0(td);
    MyThread13_1 mt1 = new MyThread13_1(td);
    mt0.start();
    mt1.start();
}
//看一下运行结果
a set over!
b set over!
b num = 200
a num = 200

According to the normal view should print "a num = 100" and "b num = 200" fishes, but now print a "b num = 200" and "a num = 200", which is thread-safety issues. We can think about is how there will be thread-safe issues:

1, mt0 first run, 100 assigned to num, and then print out "a set over!", Began to sleep

2, mt0 in sleep, mt1 run, 200 assigned to num, and then print out the "b set over!", And then print "b num = 200"

3, mt1 sleep finished sleep, because num and mt1 of mt0 of a num num is the same, so mt1 the num changed to 200, and mt0 there is no way, for it is, can only be num 100, mt0 continue to run the code print out "a num = 200"

Analysis of the causes of the problem, to solve very simple, to addNum (String userName) method to add synchronization:

On-line multi-threading method of adding synchronized keyword

public class ThreadDomain13
{
    private int num = 0;
    
    public synchronized void addNum(String userName)
    {
        try
        {
            if ("a".equals(userName))
            {
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            }
            else
            {
                num = 200;
                System.out.println("b set over!");
            } 
            System.out.println (the userName + "NUM =" + NUM); 
        } 
        the catch (InterruptedException E) 
        { 
            e.printStackTrace (); 
        } 
    } 
} 

copy the code 

look operation results: 

A SET over ! 
A NUM = 100 
B SET over ! 
B NUM = 200 is

Multiple objects multiple locks

In the synchronous case, the code in the main function be altered:

public static void main(String[] args)
{
    ThreadDomain13 td0 = new ThreadDomain13();
    ThreadDomain13 td1 = new ThreadDomain13();
    MyThread13_0 mt0 = new MyThread13_0(td0);
    MyThread13_1 mt1 = new MyThread13_1(td1);
    mt0.start();
    mt1.start();
}



看一下运行结果:

a set over!
b set over!
b num = 200
a num = 100

There is an important concept. Key lock synchronized lock objects are achieved, rather than a piece of code or methods (functions) as a lock, if this is the piece of code or methods (functions) as a lock, in fact, also acquired the object lock, just monitor (object) is different , which thread to perform the method with the synchronized keyword, which thread holds a lock which belongs to the object , other threads can only be in a wait state. But this has a premise: Since the lock is called the object lock, then bound and related objects, so multiple threads access must be the same object .

If multiple threads access is more than one object, then the Java virtual machine creates multiple locks, like the example above, creating two ThreadDomain13 objects, it creates two locks. Since two threads are held by different locks, naturally not restricted by this act of "waiting for release of the lock", you can run the code (String userName) in addNum respectively.


What synchronized (this) is locked?

Lock is the current object. When the synchronized block the contents of the executed, the current release of the lock object. The same time if multiple threads access the object, it will be blocked.
synchronized (object) locked What?

Object object is locked. When the synchronized block the contents of the executed, releases the lock object object. The same time if multiple threads access the object, it will be blocked.

It should be noted that if the object is Integer, String and so on packaging (except for the new object), and does not lock the target, it will not block the thread. Because the wrapper class is final, non-modifiable, if modifications will generate a new object. So, after a thread to modify it, other threads while acquiring the lock of the object, the object is not the original that object, it acquired another object is locked, so no obstruction.

Java in Synchronized usage: https: //blog.csdn.net/luoweifu/article/details/46613015

Guess you like

Origin www.cnblogs.com/manmanchanglu/p/11444322.html