Java thread deadlock

Source: Internet
Author: User
Tags thread thread class versions

Because a thread can enter a blocked state, and because the object may have a "sync" method--the thread cannot access that object unless the synchronization lock is lifted--so one thread is entirely likely to wait for another object, another object is waiting for the next object, and so on. The scariest thing about this "waiting" chain is getting into a closed state-the last object waiting for the first object! At this point, all threads will fall into an endless waiting state, and everyone will be unable to move. We call this a "deadlock". Although this is not often the case, once encountered, the debugging of the program will become extremely difficult.
as far as the language itself is concerned, no help is provided directly to prevent deadlocks, which we need to avoid by careful design. If there is anyone who needs to debug a deadlock program, he is not using any tricks available.

1. Java 1.2 for Stop (), suspend (), resume (), and Destroy () against
to reduce the likelihood of deadlocks, Java 1.2 makes a contribution to "object" using Thread's Stop (). Suspend (), resume (), and Destroy () methods. The
is opposed to using the stop () because it is not secure. It unlocks all locks acquired by the thread, and if the objects are in an incoherent state ("corrupted"), then other threads can check and modify them in that state. The result is a delicate situation where it is difficult to examine the real problem. So you should try to avoid using stop (), and you should use a Blocking.java method that tells a thread when to stop its execution by exiting its own run () method.
If a thread is blocked, such as when it waits for input, it is generally not possible to poll a flag as in Blocking.java. But in these cases, we should still not use stop (), instead, we should swap the interrupt () method provided by thread to abort and exit the blocked code.
 

: Interrupt.java//The alternative approach to using stop ()//Where a thread is blocked import java.awt.*;
Import java.awt.event.*;

Import java.applet.*; Class Blocked extends Thread {public synchronized void run () {try {wait ();//Blocks} catch (Interrupte
    Dexception e) {System.out.println ("interruptedexception");
  } System.out.println ("Exiting Run ()");
  } public class Interrupt extends Applet {private button Interrupt = new Button ("Interrupt");
  Private Blocked Blocked = new Blocked ();
    public void Init () {Add (interrupt);
          Interrupt.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {
          SYSTEM.OUT.PRINTLN ("button pressed");
          if (blocked = null) return;
          Thread remove = blocked; blocked = null;
        To release it Remove.interrupt ();
    }
      });
  Blocked.start (); public static void Main (string[] args) {inteRrupt applet = new Interrupt ();
    Frame aframe = new Frame ("Interrupt"); Aframe.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {System.
        Exit (0);
    }
      });
    Aframe.add (applet, borderlayout.center);
    Aframe.setsize (200,100);
    Applet.init ();
    Applet.start ();
  Aframe.setvisible (TRUE); }
} ///:~

The wait () inside the


Blocked.run () produces a blocked thread. When we press the button, the blocked (blocked) handle is set to null so that the garbage collector can purge it, and then call the object's interrupt () method. If the button is pressed for the first time, we will see the thread exit normally. But when there is no "kill" thread, all you see is a button being pressed. The
Suspend () and resume () methods are inherently prone to deadlocks. When the suspend () is invoked, the target line Cheng stops, but still holds the lock acquired prior to that. At this point, no other thread can access the locked resource unless it is resumed by a "pending" thread. For any thread, if they want to recover the target thread while attempting to use any of the locked resources, it can cause an embarrassing deadlock. So instead of using suspend () and resume (), we should place a flag in our thread class that indicates whether the thread should be active or suspended. If the flag indicates that the thread should be suspended, use wait () to get it into the waiting state. If the flag indicates that the thread should be restored, restart the thread with a notify (). We can modify the previous Counter2.java to actually experience it. Although the two versions have the same effect, you'll notice that the code's organizational structure has changed a lot--anonymous internal classes are used for all audiences, and thread is an internal class. This makes the program a little easier to write because it cancels out some of the extra recording work in the Counter2.java.
 

: Suspend.java//The alternative approach to using Suspend ()//and resume (), which have been deprecated//in Java 1.
2. Import java.awt.*;
Import java.awt.event.*;

Import java.applet.*;
  public class Suspend extends Applet {private TextField t = new TextField (10);
  Private button suspend = New button ("Suspend"), Resume = New button ("Resume");
    Class Suspendable extends Thread {private int count = 0;
    Private Boolean suspended = false;
    Public suspendable () {Start ();}
    public void Fauxsuspend () {suspended = true;
      Public synchronized void Fauxresume () {suspended = false;
    Notify ();
          public void Run () {while (true) {try {100);
          Synchronized (this) {while (suspended) wait ();
      The catch (Interruptedexception e) {} t.settext (integer.tostring (count++));
  }} private Suspendable SS = new suspendable (); public void Init () {Add (t);
          Suspend.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {
        Ss.fauxsuspend ();
    }
      });
    Add (suspend);
          Resume.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {
        Ss.fauxresume ();
    }
      });
  Add (resume);
    public static void Main (string[] args) {Suspend applet = new Suspend ();
    Frame aframe = new Frame ("Suspend"); Aframe.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {SYSTEM.E
        XIT (0);
    }
      });
    Aframe.add (applet, borderlayout.center);
    Aframe.setsize (300,100);
    Applet.init ();
    Applet.start ();
  Aframe.setvisible (TRUE); }
} ///:~


The suspended (suspended) flag in suspendable is used for the switch "suspend" or "suspend" status. To suspend a thread, simply call Fauxsuspend () to set the flag to True (true). The detection of the flag status is performed in run (). As mentioned earlier in this chapter, wait () must be set to "Sync" (synchronized) to enable it to use object locks. In Fauxresume (), the suspended flag is set to False (False) and call Notify ()--since this will wake up wait () in a "sync" clause, the Fauxresume () method must also be synchronized so that it can invoke notify () Gets the object lock before (this allows the object lock to be used by the wait () to call Shoppes). If you follow the style shown in this procedure, you can avoid the use of Wait () and notify ().
The Destroy () method of thread is not implemented at all, it resembles a suspend () that cannot be recovered at all, and so a deadlock problem like suspend () occurs. However, this approach is not explicitly "opposed" and may be implemented in later versions of Java (after version 1.2) for special occasions that can withstand deadlock risks.
You may wonder why you were trying to achieve these things that are now "opposed". This is probably due to the fact that sun is primarily allowing technicians to decide on language changes, not the marketing staff. In general, technicians understand the essence of language better than those who engage in sales. When you make a mistake, you can face them more rationally. This means that Java can continue to improve, even if it makes Java programmers somewhat inconvenient. As far as I am concerned, I would rather face these inconveniences than to see language stagnate.

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.