Go: "Java concurrent Programming" bis: Thread Break (with code)

Source: Internet
Author: User
Tags thread class

Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17091267


use interrupt () to break the thread

When one thread is running, another thread can call the interrupt () method of the corresponding thread object to break it, and the method simply sets a flag in the target thread that indicates that it has been interrupted and returns immediately. It is important to note that if you simply call the interrupt () method, the thread is not actually interrupted and will continue to execute.

The following code demonstrates the interruption of a dormant thread:

[Java]View PlainCopy
  1. Public class Sleepinterrupt extends Object implements runnable{
  2. public Void Run () {
  3. try{
  4. System.out.println ("in Run ()-about to sleep for seconds");
  5. Thread.Sleep (20000);
  6. System.out.println ("in Run ()-Woke up");
  7. }catch (Interruptedexception e) {
  8. System.out.println ("in Run ()-interrupted while sleeping");
  9. //After processing the interrupt exception, return to the Run () method population,
  10. //If there is no return, the thread will not actually be interrupted, it will continue to print the following information
  11. return;
  12. }
  13. System.out.println ("in Run ()-leaving normally");
  14. }
  15. public static void Main (string[] args) {
  16. Sleepinterrupt si = new Sleepinterrupt ();
  17. Thread t = new Thread (SI);
  18. T.start ();
  19. //The main thread sleeps for 2 seconds, thus ensuring that threads just started have a chance to execute for some time
  20. try {
  21. Thread.Sleep (2000);
  22. }catch (Interruptedexception e) {
  23. E.printstacktrace ();
  24. }
  25. System.out.println ("in Main ()-interrupting other thread");
  26. //middle thread T
  27. T.interrupt ();
  28. System.out.println ("in Main ()-leaving");
  29. }
  30. }

The results of the operation are as follows:


after the main thread starts the new threads, it sleeps for 2 seconds, allowing the new thread to get run time. After the new thread prints the information "about-to-sleep for seconds", and then sleeps for 20 seconds, after about 2 seconds, the main thread notifies the new thread of the break, then the new thread's 20-second sleep is interrupted, causing the interruptexception exception to be thrown, Executes a jump to a catch block, prints out "interrupted while sleeping" information, and immediately returns from the run () method, and then dies, without printing the "leaving normally" message after the catch block. Note: Because of an indeterminate thread plan, the latter two rows of the result may be in reverse order, depending on the primary thread and the new thread which first dies. But the order of the first two lines of information must be as shown. In addition, if the return statement in the Catch block is commented out, the thread will continue to execute until the exception is thrown, without interruption, and the "leaving normally" message will be printed.

pending Interrupts

In the example above, the implementation of the sleep () method checks that the dormant thread is interrupted, it terminates the thread fairly nicely, and throws a Interruptedexception exception. In another case, if the thread is interrupted before calling the sleep () method, then the interrupt is called a pending interrupt, and it throws the interruptedexception exception immediately when the sleep () method is called .

The following code shows the pending interrupt:

[Java]View PlainCopy
  1. Public class Pendinginterrupt extends Object {
  2. public static void Main (string[] args) {
  3. //If a parameter is entered, the current thread (i.e. the main thread) is interrupted in the Mian thread
  4. if (Args.length > 0) {
  5. Thread.CurrentThread (). interrupt ();
  6. }
  7. //Get current time
  8. Long startTime = System.currenttimemillis ();
  9. try{
  10. Thread.Sleep (2000);
  11. System.out.println ("is not interrupted");
  12. }catch (Interruptedexception x) {
  13. System.out.println ("was interrupted");
  14. }
  15. //Calculate the time of intermediate code execution
  16. System.out.println ("elapsedtime=" + (System.currenttimemillis ()-startTime));
  17. }
  18. }

If the pendinginterrupt does not have any command line arguments, then the thread will not be interrupted, the final output time gap should be near 2000 (the time is determined by the system, not accurate), if pendinginterrupt with command-line arguments, the call interrupts the current thread of the code , but the main thread is still running and the final output time gap should be much less than 2000 because the thread has not yet been dormant and is interrupted, so once the sleep () method is called, the information in the catch block is printed immediately. The results of the implementation are as follows:

in this mode, the main thread interrupts itself. In addition to setting the interrupt flag (which is the internal flag of thread) to true, there is no other effect. The thread is interrupted, but the main thread is still running, the main thread continues to monitor the real-time clock and enters the try block, and once the Sleep () method is called, it will notice the existence of the pending interrupt and throw interruptexception. The execution jumps to the catch block and prints the information that the thread is interrupted. Finally, the time difference is calculated and printed.

Use the isinterrupted () method to determine the interrupt stateYou can call the Isinterrupted () method on the thread object to check the interrupt state of any thread. Note here: Once the thread is interrupted, the isinterrupted () method returns True, and once the sleep () method throws an exception, it empties the interrupt flag, and the Isinterrupted () method returns FALSE.
The following code demonstrates the use of the Isinterrupted () method:
[Java]View PlainCopy
  1. Public class Interruptcheck extends object{
  2. public static void Main (string[] args) {
  3. Thread t = Thread.CurrentThread ();
  4. System.out.println ("point a:t.isinterrupted () =" + t.isinterrupted ());
  5. //Pending interrupt, interrupt itself
  6. T.interrupt ();
  7. System.out.println ("point b:t.isinterrupted () =" + t.isinterrupted ());
  8. System.out.println ("point c:t.isinterrupted () =" + t.isinterrupted ());
  9. try{
  10. Thread.Sleep (2000);
  11. System.out.println ("is not interrupted");
  12. }catch (Interruptedexception x) {
  13. System.out.println ("was interrupted");
  14. }
  15. //Throws an exception, clears the interrupt flag and returns false
  16. System.out.println ("point d:t.isinterrupted () =" + t.isinterrupted ());
  17. }
  18. }
The results of the operation are as follows:

Use the thread.interrupted () method to determine the interrupt state

You can use the thread.interrupted () method to check the interrupt state of the current thread (and implicitly reset to false). This method returns true because it is a static method and therefore cannot be used on a particular thread, only the interrupt state of the thread that called it is reported, and if the thread is interrupted and the interrupt state is unclear. Unlike isinterrupted (), it automatically resets the interrupt state to false, the second call to the Thread.interrupted () method, and always returns false unless the thread is interrupted.

The following code demonstrates the use of the Thread.interrupted () method:

[Java]View PlainCopy
  1. Public class Interruptreset extends Object {
  2. public static void Main (string[] args) {
  3. System.out.println (
  4. "Point x:thread.interrupted () =" + thread.interrupted ());
  5. Thread.CurrentThread (). interrupt ();
  6. System.out.println (
  7. "Point y:thread.interrupted () =" + thread.interrupted ());
  8. System.out.println (
  9. "Point z:thread.interrupted () =" + thread.interrupted ());
  10. }
  11. }

The results of the operation are as follows:

As can be seen from the results, after the current thread breaks itself, at the y Point, the interrupt state is true and is automatically reset to False by thread.interrupted (), then the next call to the method results in false.


Supplement This is supplemented by the use of yield and join methods.
The join method is called with the thread object, and if you call another thread B's Join method in a thread A, thread a waits for thread B to execute before executing. yield can be called directly with the thread class, yielding yields the CPU execution to the same level of thread, and if no thread of the same level waits for the CPU to execute, the thread continues execution.

Go: "Java concurrent Programming" bis: Thread Break (with code)

Related Article

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.