Java multi-thread Support (2)-thread deadlock

Source: Internet
Author: User
Tags sleep function

We know that when thread A gives up the execution right for some reason (such as waiting for the completion of IO operations or calling the sleep function), the operating system will schedule another ready state (Runnable) thread B. Only when the event waiting for thread A occurs (such as IO operation completed and sleep time ended) will thread A be set to ready and wait for the scheduling of the operating system.

However, sometimes there may be A situation where thread A is in the blocking state (blocked) to wait for thread B. At this time, thread B is in the blocking state while waiting for thread. At this time, both A and B are waiting for each other. Therefore, neither A nor B can receive execution opportunities. This kind of phenomenon that these threads cannot be executed due to mutual waiting of threads is called a thread deadlock.

 


Next we will manually cause a thread deadlock to understand the concept of a deadlock.

Note that in Java, the synchronized keyword can also be used to declare a method, such as public synchronized run (). A synchronous method is to request the monitor of this object to implement synchronization, which is a prerequisite for understanding the following programs.

We first define a ThreadLock class that implements the Runnable interface, then define a synchronous method fun (), and define a synchronous block for the request Object within this method;

Define a synchronization block for the request Object in the run () method, and then define a synchronization block for the request this Object;

The description is abstract, so let's go directly to the code ..

 

 

[Java]
Package cls;
 
Public class ThreadLockDemo
{
 
/**
* @ Param args
*/
Public static void main (String [] args)
{
ThreadLock tl = new ThreadLock ();

New Thread (tl). start ();
New Thread (tl). start ();
}
}
 
Class ThreadLock implements Runnable
{
Private Object obj = new Object (); // Synchronized Object
Boolean bool = false ;//

// Synchronized method run ()
Public void run ()
{
If (bool = true)
{
Fun ();
}
Else
{
Synchronized (obj)
{
Bool = true;
// Sleep for a while, give up running.
Try
{
Thread. sleep (50 );
}
Catch (Exception e)
{
E. printStackTrace ();
}

// Enter the synchronized block, using this Object.
Synchronized (this)
{
System. out. println (Thread. currentThread (). getName () + "is running! ");
}
}
}
}
// Synchronized method fun ()
Public synchronized void fun ()
{
Synchronized (obj)
{
While (true)
{
System. out. println (Thread. currentThread (). getName () + "is running! ");
}
}
}
}

Package cls;

Public class ThreadLockDemo
{

/**
* @ Param args
*/
Public static void main (String [] args)
{
ThreadLock tl = new ThreadLock ();

New Thread (tl). start ();
New Thread (tl). start ();
}
}

Class ThreadLock implements Runnable
{
Private Object obj = new Object (); // Synchronized Object
Boolean bool = false ;//
 
// Synchronized method run ()
Public void run ()
{
If (bool = true)
{
Fun ();
}
Else
{
Synchronized (obj)
{
Bool = true;
// Sleep for a while, give up running.
Try
{
Thread. sleep (50 );
}
Catch (Exception e)
{
E. printStackTrace ();
}

// Enter the synchronized block, using this Object.
Synchronized (this)
{
System. out. println (Thread. currentThread (). getName () + "is running! ");
}
}
}
}
// Synchronized method fun ()
Public synchronized void fun ()
{
Synchronized (obj)
{
While (true)
{
System. out. println (Thread. currentThread (). getName () + "is running! ");
}
}
}
}

When we execute this program, we find that there is no output result, and the program does not exit at this time. At this time, the two threads in the program will not be able to execute because they are waiting for the other side, causing a deadlock.

Let's analyze the process of deadlock in this program:

First, thread A starts and the bool value is false. Execute the else branch in the run () method, lock the obj object, change bool to true, and then sleep. At this time, A has waived the execution right.

When thread B starts, and bool value is true, the first branch in the run () method is executed and the fun () method is called. Because fun () is a synchronous method, it will check whether this object has been locked and the result is no, so the program enters the fun () method, and lock this object. Then we encountered the synchronized (obj) Synchronization block. Because thread A has locked the obj object, thread B cannot enter the synchronization block and can only wait.

At this time, thread A's sleep time reaches and continues to execute from the last interrupted place, so it encounters A synchronized (this) Synchronization block. Because thread B has just locked this object, thread A cannot enter the synchronization block and can only wait.

In this case, the deadlock between threads A and B is formed.

 


In multi-threaded program design, thread synchronization is a very complicated problem. Once the processing is poor, it is very likely that such a problem occurs. In practice, we must be careful to avoid such errors.


 

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.