Java thread deadlock

Source: Internet
Author: User
 

Deadlock: Multiple threads are blocked at the same time, and one or all of them are waiting for the release of a resource. The program cannot run properly because the thread is blocked indefinitely. Simply put, when a thread is deadlocked, the first thread waits for the second thread to release resources, and the second thread is waiting for the first thread to release resources. The root cause of the deadlock is the improper use of the "synchronized" keyword to manage the thread's access to specific objects.

Inter-thread Communication: Multiple threads operate on the same resource in the thread, but the operations are different.

The following is an example of communication between two threads. If synchronization is not used, the name and sex may not be synchronized:

Class Res {// shared resource String name; String sex;} class Input implements Runnable {// -------------- use 1 private Res r; Input (Res r) {this. r = r;} public void run () {int x = 0; while (true) {synchronized (Input. class) {// and the following must be Input. class or Output. class. In short, the upper and lower thread locks must be consistent to synchronize if (x = 0) {r. name = "mike"; r. sex = "man";} else {r. name = "Lili"; r. sex = "female and female" ;}x = (x + 1) % 2 ;}}} class Output implements Runnable {private Res r; Output (Res r) {this. r = r;} public void run () {while (true) synchronized (Input. class) {System. out. println (r. name + "----" + r. sex) ;}} public class Test {public static void main (String [] args) {Res r = new Res (); Input in = new Input (r ); output out = new Output (r); Thread t1 = new Thread (in), t2 = new Thread (out); t1.start (); t2.start ();}}

Result: Lili-female and female
Lili ---- female and female
Lili ---- female and female
Mike ---- man
Mike ---- man

Wait (), Policy (), policyall ()

These three methods are used to coordinate multiple threads to access Shared data. Therefore, these three methods must be used in the Synchronized statement block. Synchronized is used to protect shared data, but the process of the program is not flexible. At this time, these three methods are used for flexible control.
The thread can call the wait () method of the object to suspend the execution of the current thread andRelease object lock flagTo enter the waiting state, and you can call the Y () or notifyAll () method to notify other waiting threads, and then wait for the notify of the same thread lock, the content that has not been completed after continuing to run wait. Y () notifies the first thread in the waiting queue. notifyAll () notifies all threads in the waiting queue.
Note that all three methods are java. lang. Ojbect methods! Why are the methods of these operation threads defined in the Object? These methods must mark only the locks of the threads they operate on during synchronization. Only the waiting threads of the same lock can be awakened by Y of the same lock. It is not allowed to wake up threads in different locks. That is to say, wait and wake-up must be the same lock, and the lock can be any Object, so the method called by any Object can be defined in the Object.
If both A1, A2, and A3 are in obj. wait (), B calls obj. Y () to wake up only one of A1, A2, and A3.
Change the output in the above example to alternate output:

Class Res {// shared String name; String sex; boolean flag = false;} class Input implements Runnable {private Res r; Input (Res r) {this. r = r;} public void run () {int x = 0; while (true) {synchronized (r) {if (r. flag) try {// -------- interface exception cannot be repeated r. wait ();} catch (InterruptedException e) {e. printStackTrace ();} if (x = 0) {r. name = "mike"; r. sex = "man";} else {r. name = "Lili"; r. sex = "female and female";} x = (x + 1) % 2; r . Flag = true; r. notify () ;}}} class Output implements Runnable {private Res r; Output (Res r) {this. r = r;} public void run () {while (true) synchronized (r) {if (! R. flag) try {r. wait ();} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (r. name + "----" + r. sex); r. flag = false; r. policy () ;}} public class Test {public static void main (String [] args) {Res r = new Res (); Input in = new Input (r ); output out = new Output (r); Thread t1 = new Thread (in), t2 = new Thread (out); t1.start (); t2.start ();}}

The following are producer and consumer issues (multiple producers and consumers). Each product is consumed

Class Resource {private String name; private int count = 1; private boolean flag = false; public synchronized void set (String name) {while (flag) try {wait ();} catch (Exception e) {} this. name = name + "----" + count ++; System. out. println (Thread. currentThread (). getName () + "---- producer ----" + this. name); flag = true; this. policyall ();} public synchronized void out () {while (! Flag) try {wait ();} catch (Exception e) {} System. out. println (Thread. currentThread (). getName () + "---- consumer ---------" + this. name); flag = false; this. yyall (); // replace policy with policyall} class Producer implements Runnable {private Resource res; Producer (Resource res) {this. res = res;} public void run () {while (true) res. set ("+ item +") ;}} class Consumer implements Runnable {private Resource res; Consumer (Resource res) {this. res = res;} public void run () {while (true) res. out () ;}} class Test {public static void main (String [] args) {Resource r = new Resource (); Producer pro = new Producer (r ); consumer con = new Consumer (r); Thread t1 = new Thread (pro), t2 = new Thread (pro), t3 = new Thread (con ), t4 = new Thread (con); t1.start (); t2.start (); t3.start (); t4.start ();}}

Although synchronized methods and the range mechanism of statements make it much easier to use the monitor lock programming, it also helps avoid many common programming errors related to locks, but sometimes the lock needs to be used in a more flexible way. JDK provides a multi-thread upgrade solution, which replaces synchronous synchronized with the actual Lock operation and replaces wait, policy, and policyall in the Object with the Condition Object, the Lock implementation provides a wider range of Lock operations than the synchronized Method and statement. This implementation allows a more flexible structure, can have very different attributes, can support multiple related
Condition object.

Condition splits the Object monitor methods (wait, policy, and policyall) into distinct objects so that they can be combined with any Lock implementation, multiple waiting sets (wait-set) are provided for each object ). Here, Lock replaces the use of synchronized methods and statements, and Condition replaces the use of Object monitor methods.

The following uses lock to implement producer consumers:

Import java. util. concurrent. locks. *; class Resource {private String name; private int count = 1; private boolean flag = false; private Lock lock = new ReentrantLock (); // private Condition condition_pro = lock. newCondition (); // private Condition condition_con = lock. newCondition (); // public void set (String name) throws InterruptedException {lock. lock (); // try {while (flag) condition_pro.await ();// /This. name = name + "----" + count ++; System. out. println (Thread. currentThread (). getName () + "---- producer ----" + this. name); flag = true; condition_con.signal (); //} finally {lock. unlock (); //} public void out () throws InterruptedException {lock. lock (); // try {while (! Flag) condition_con.await (); // System. out. println (Thread. currentThread (). getName () + "---- consumer ---------" + this. name); flag = false; condition_pro.signal () ;}finally {lock. unlock () ;}} class Producer implements Runnable {private Resource res; Producer (Resource res) {this. res = res;} public void run () {while (true) try {res. set ("+ item +");} catch (Exception e) {}} class Consumer implements Runnable {private Resource res; Consumer (Resource res) {this. res = res;} public void run () {while (true) try {res. out () ;}catch (Exception e) {}} class Test {public static void main (String [] args) {Resource r = new Resource (); producer pro = new Producer (r); Consumer con = new Consumer (r); Thread t1 = new Thread (pro), t2 = new Thread (pro ), t3 = new Thread (con), t4 = new Thread (con); t1.start (); t2.start (); t3.start (); t4.start ();}}

Thread interruption: Define the end mark of the loop, because the code of the thread is usually a loop, as long as the loop is controlled. In special cases, when the thread is frozen, the mark cannot be read, and the interrupt () method is used, stops the thread freezing and returns the thread to the running status,However, an InterruptedException exception occurs.

The stop method is no longer used.

Interrupt (): If the thread calls the wait (), wait (long), or wait (long, int) Methods of the Object class, or the join (), join (long) when the join (long, int), sleep (long), or sleep (long, int) method is blocked, the disconnection state is cleared, and InterruptedException is also received.

Class StopThread implements Runnable {private boolean flag = true; public synchronized void run () {while (flag) {try {wait ();} catch (InterruptedException e) {// process the dynamic completion status System. out. println (Thread. currentThread (). getName () + "---- Exception"); flag = false;} System. out. println (Thread. currentThread (). getName () + "---- run") ;}} public void changeFlag () {flag = false ;}} class Test {public static void main (String [] args) {StopThread st = new StopThread (); Thread t1 = new Thread (st), t2 = new Thread (st); t1.start (); t2.start (); int num = 0; while (true) {if (num ++ = 60) {// st. changeFlag (); t1.interrupt (); t2.interrupt (); break;} System. out. println (Thread. currentThread (). getName () + "-----" + num);} System. out. println ("over ");}}

Background thread: SetDaemon (boolean on) marks this thread as a daemon or user thread. When all running threads are daemon threads, the program ends and the Java Virtual Machine exits.

Yield () sleep () wait () Difference

Sleep ()
Pause the current thread for a period of time, so that other threads have the opportunity to continue the execution, but when it is its turn to execute, it does not execute the run method, but the pause does not affect cpu scheduling, but it does not release the object lock. That is, if there is a Synchronized synchronization block, other threads still access Shared data differently.
Join ()T. join (),Running threadIt is executed after the t thread finishes running, that is, it waits until the thread that calls the method finishes executing it. If there are multiple threads, other threads are not affected.
Yield ()Similar to sleep (), the user cannot specify the duration of the pause.
Wait ()After wait (), the thread will release the lock mark it occupies, so that other synchronized data in the thread's object can be used by other threads.

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.