Seven. Multithreaded programming 11. Thread suspend, resume, and terminate

Source: Internet
Author: User
Tags thread class

Tag: instance does not have res Zed End final system BSP operation

Sometimes, thread hangs are useful. For example, a separate thread can be used to display the time of day. If the user does not want to use the clock, the thread is suspended. In any case, suspending a thread is simple, and once suspended, restarting the thread is also a simple matter.

Pending, the termination and recovery threading mechanism differs in Java 2 and earlier versions. Although you write code in Java 2, you still need to understand how these operations are done in the early Java environment. For example, you might need to update or maintain the old code. You also need to understand why Java 2 has this kind of change. For these reasons, the following describes the original method of executing thread control, followed by the Java 2 method.

Suspend, resume, and terminate threads for Java 1.1 or earlier

Before the JAVA2 version, the program pauses and restarts the thread with the suspend () and resume () defined by the thread. They are in the following form:
Final void Suspend ()
Final void Resume ()
The following procedures describe these methods:
Using suspend () and resume ().
Class Newthread implements Runnable {
String name; Name of Thread
Thread T;
Newthread (String threadname) {
name = ThreadName;
t = new Thread (this, name);
System.out.println ("New thread:" + t);
T.start (); Start the thread
}
The entry point for thread.
public void Run () {
try {
for (int i = +; i > 0; i--) {
SYSTEM.OUT.PRINTLN (name + ":" + i);
Thread.Sleep (200);
}
} catch (Interruptedexception e) {
SYSTEM.OUT.PRINTLN (name + "interrupted.");
}
SYSTEM.OUT.PRINTLN (name + "exiting.");
}
}
Class Suspendresume {
public static void Main (String args[]) {
Newthread ob1 = new Newthread ("one");
Newthread ob2 = new Newthread ("both");
try {
Thread.Sleep (1000);
Ob1.t.suspend ();
System.out.println ("Suspending thread One");
Thread.Sleep (1000);
Ob1.t.resume ();
System.out.println ("Resuming thread One");
Ob2.t.suspend ();
System.out.println ("Suspending thread");
Thread.Sleep (1000);
Ob2.t.resume ();
System.out.println ("Resuming thread");
} catch (Interruptedexception e) {
System.out.println ("Main thread Interrupted");
}
Wait for threads to finish
try {
System.out.println ("Waiting for threads to finish.");
Ob1.t.join ();
Ob2.t.join ();
} catch (Interruptedexception e) {
System.out.println ("Main thread Interrupted");
}
System.out.println ("Main thread exiting.");
}
}
Part of the output of the program is as follows:
New Thread:thread[one,5,main]
One:15
New Thread:thread[two,5,main]
Two:15
One:14
Two:14
One:13
Two:13
One:12
Two:12
One:11
Two:11
Suspending Thread One
Two:10
Two:9
Two:8
Two:7
Two:6
Resuming Thread One
Suspending thread
One:10
One:9
One:8
One:7
One:6
Resuming thread
Waiting for threads to finish.
Two:5
One:5
Two:4
One:4
Two:3
One:3
Two:2
One:2
Two:1
One:1
The exiting.
One exiting.
Main thread exiting.

The thread class also defines stop () to terminate the thread. It has the following form:
void Stop ()
Once the thread is terminated, it cannot be resumed by resume ().

Suspend, resume, and terminate threads in Java 2

The thread-defined suspend (), resume (), and Stop () methods appear to be the perfect and convenient way to manage threads, and they cannot be used in new Java versions of the program. Here's why. The suspend () method of the thread class is not approved in JAVA2 because suspend () sometimes causes a serious system failure. Assuming that a thread is locked on a critical data structure, if the thread is suspended there, these locked threads do not relinquish control of the resource. Other threads that wait for these resources may deadlock.

The Resume () method is also not approved. It does not cause problems, but it cannot be used independently from the Suspend () method. The Stop () method of the thread class was also objected to in Java 2. This is because the method can cause a serious system failure. Imagine that a thread is writing a sophisticated, important data structure and only a fraction of the total is done. If the thread terminates at this point, the data structure may be stuck in a collapsed state.

Because in Java 2 You cannot use the suspend (), resume (), and Stop () methods to control threads, you might think that there is no way to stop, resume, and end threads. actually otherwise Instead, the thread must be designed so that the run () method periodically checks to see if the thread should be suspended, or to resume or terminate its own execution. Representative, this is done by establishing a flag variable that indicates the state of the thread. As long as the flag is set to "running", the Run () method must continue to be executed by the thread. If the flag is "suspend", the thread must be paused. If set to "Stop", the thread must terminate.

Of course, there are many ways to write such code, but the central theme should be the same for all programs.

The following example illustrates how the wait () and notify () methods inherited from object control the execution of threads. This example is similar to the procedure described earlier. However, the methods that are not approved are not used. Let's think about the execution of the program.

The Newtread class contains an instance variable SuspendFlag that is used to control the execution of a thread in a Boolean type. It is initialized to false by the constructor. The Run () method contains a block that monitors the suspendflag of a synchronous declaration. If the variable is true,wait () the method is called to suspend the thread. The Mysuspend () method sets SuspendFlag to True. The Myresume () method sets SuspendFlag to false and calls the Notify () method to invoke the thread. Finally, the main () method is modified to invoke the Mysuspend () and Myresume () methods.
Suspending and resuming a thread for JAVA2
Class Newthread implements Runnable {
String name; Name of Thread
Thread T;
Boolean SuspendFlag;
Newthread (String threadname) {
name = ThreadName;
t = new Thread (this, name);
System.out.println ("New thread:" + t);
SuspendFlag = false;
T.start (); Start the thread
}
The entry point for thread feifanyule.cn.
public void Run () {
try {
for (int i = +; i > 0; i--) {
SYSTEM.OUT.PRINTLN (name + ":" + i);
Thread.Sleep (200);
Synchronized (this) {
while (SuspendFlag) {
Wait ();
}
}
}
} catch (Interruptedexception e) {
SYSTEM.OUT.PRINTLN (name + "interrupted.");
}
SYSTEM.OUT.PRINTLN (name + "exiting.");
}
void Mysuspend () {
SuspendFlag = true;
}
synchronized void Myresume () {
SuspendFlag = false;
Notify ();
}
}
Class Suspendresume {
public static void Main (String args[]) {
Newthread ob1 = new Newthread ("one");
Newthread ob2 = new Newthread ("both");
try {
Thread.Sleep (1000);
Ob1.mysuspend ();
System.out.println ("Suspending thread One");
Thread.Sleep (1000);
Ob1.myresume ();
System.out.println ("Resuming thread One");
Ob2.mysuspend ();
System.out.println ("Suspending thread");
Thread.Sleep (1000);
Ob2.myresume ();
System.out.println ("Resuming thread");
} catch (Interruptedexception e) {
System.out.println ("Main thread Interrupted");
}
Wait for threads to finish
try {
System.out.println ("Waiting for threads to finish.");
Ob1.t.join ();
Ob2.t.join ();
} catch (Interruptedexception e) {
System.out.println ("Main thread Interrupted");
}
System.out.println ("Main thread exiting.");
}
}
The output of the program is the same as the previous program. Later in this book, you'll see more examples of controlling threads with the Java 2 mechanism. Although this mechanism is not as "clean" as the old method, it is a way to ensure that no errors occur at run time. It is the method that all new code must adopt.

Seven. Multithreaded programming 11. Thread suspend, resume, and terminate

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.