Deep understanding of built-in locks and deadlocks in Java 02

Source: Internet
Author: User

I. Concurrent problem analysis

If an interface provided by a class or program is an atomic operation for a thread, or the switching between multiple threads does not result in ambiguity in the execution result of the interface, that is to say, we do not need to consider the synchronization problem. At this time, the thread is secure.

In reality, this situation exists:
1. There are two or more thread objects, and one resource is shared between threads.
2. Multiple statements operate on shared resources.

II. Solutions

Use a case study: Zhang Liuliang and Zheng Xu share a pack of paper. Two people are equivalent to two threads, and each piece of paper cannot be extracted simultaneously.
Method 1: synchronize code blocks
Thread class:


Class PaperThread extends Thread {
        
Static int num = 100; // The number of non-static member variables in the paper. The non-static member variable data maintains a copy of data in each object.
     
Static Object o = new Object ();
    
Public PaperThread (String name ){
Super (name );
     }
    
@ Override
Public void run (){
While (true ){
// Synchronize code blocks
Synchronized ("lock "){
If (num> 0 ){
System. out. println (Thread. currentThread (). getName ()
+ "1 piece of paper is taken away, and" + (count-1) + "Zhang "");
Try {
Thread. sleep (100 );
} Catch (InterruptedException e ){
E. printStackTrace ();
                    }
Num --;
} Else {
System. out. println ("used up ..");
Break;
                }
            }     
        }
    }     
}

Test class
    
Public class Test {
Public static void main (String [] args ){
// Create two threads
PaperThread thread1 = new PaperThread ("Zhang Liuliang ");
PaperThread thread2 = new PaperThread ("Zheng Xu ");
// Enable the thread
Thread1.start ();
Thread2.start ();
    } 
}

Precautions for synchronizing code blocks:

1. Any object can be used as a lock object.
2. The sleep method called in the synchronization code block is not used to release the lock object.
3. Use the synchronization code block only when there is a real thread security problem. Otherwise, the efficiency will be reduced.
4. The lock object for multi-threaded operations must be unique and shared; otherwise, the lock object is invalid.

Method 2: synchronous function: the synchronous function uses synchronized to modify a function.
Thread class:


Class PaperThread extends Thread {
    
Static int count = 100;
    
Public currentThread (String name ){
Super (name );
    }
    
    // @ Override
Public synchronized void run (){
GetPaper ();
    } 
    
// Static functions ----> bytecode file object of the class to which the function belongs ---> PaperThread. class is unique.
Public static synchronized void getPaper (){
While (true ){
If (count> 0 ){
System. out. println (Thread. currentThread (). getName ()
+ "1 piece of paper is taken away, and" + (count-1) + "");
Count = count-1000;
} Else {
System. out. println ("paper out ...");
Break;
            } 
        }
    } 
}
Test class:

Public class Test {
 
Public static void main (String [] args ){
// Create two thread objects
PaperThread thread1 = new PaperThread ("Zhang Liuliang ");
PaperThread thread2 = new PaperThread ("Zheng Xu ");
// Call the start method to enable the thread to get the money
Thread1.start ();
Thread2.start ();
    } 
}
Notes for synchronous functions:
1. if the lock object of a non-static synchronous function is this object, if the lock object of the static synchronous function is the bytecode File (class object) of the class to which the current function belongs ).
2. The lock objects of synchronization functions are fixed and cannot be specified by you.

Recommended: synchronous code block.
Cause:
1. The lock objects of the synchronized code block can be randomly specified for convenient control. The lock object of the synchronous function is fixed and cannot be specified by us.
2. The synchronization code block can easily control the scope of the code to be synchronized. The synchronous function must be synchronized to all the code of the entire function.

3. Deadlock

The synchronization mechanism solves thread security issues, but also causes deadlocks.
Case: Zhang Liuliang and Zheng Xu played LOL with only one mouse and one keyboard. They needed both the mouse and the keyboard to play LOL.


Class DeadLock extends Thread {
    
Public DeadLock (String name ){
Super (name );
    }
    
Public void run (){
If ("Zhang Liuliang". equals (Thread. currentThread (). getName ())){
Synchronized ("keyboard "){
System. out. println ("Zhang Liu Liang got the keyboard and prepared to take the mouse ");
Synchronized ("mouse "){
System. out. println ("Zhang Liu Liang picked up the keyboard and mouse ");
                }
            }
} Else if ("Zheng Xu". equals (Thread. currentThread (). getName ())){
Synchronized ("mouse "){
System. out. println ("Zheng Xu took the mouse and prepared to take the keyboard ");
Synchronized ("keyboard "){
System. out. println ("Zheng Xu picked up the keyboard and mouse ");
                }
            }     
        } 
    }
}


Public class TestDeadLock {
 
Public static void main (String [] args ){
DeadLock thread1 = new DeadLock ("Liu Liang Zhang ");
DeadLock thread2 = new DeadLock ("Zheng Xu ");
// Enable the thread
Thread1.start ();
Thread2.start ();
        
    }
    
}
Root cause of deadlock:
1. There are two or more threads.
2. Two or more shared resources exist.
Solution to the deadlock phenomenon: there is no solution to the deadlock, which can only be avoided as much as possible.

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.