Methods for pausing and continuing other threads in the Java GUI

Source: Internet
Author: User

In the Java GUI, what if you want to be able to interactively control the pauses and continuation of threads outside the main thread of a control through a button or other user? This is a way I think of.

A link to the Java API documentation is provided here: http://docs.oracle.com/javase/8/docs/api/index.html. Refer to the thread class inside the Java.lang package, this class of suspend is not recommended, using the method is not safe. In fact, each object has a wait () inverse, and we use this method.

You create a class that inherits the thread class, which defines two variables:

1  Public New Object (); 2  Public Boolean false;

where obj can be substituted with any object, just use it to provide the wait () method; Issuspend is a Boolean variable, False is pending, true is pending, and is initialized to false. Of course member variables should be defined as private, for convenience.

Then, define a method in the class:

1      Public voidsetsuspends ()2     {3          while(issuspend)4         {5             synchronized(obj)6             {7                 Try{8Obj.wait (10);//the size is random, the small point is better9                 }Ten                 Catch(interruptedexception e) One                 { A                 } -             } -         }    the}

Then, add the following code to the event listener for the control on the main thread:

1 Private void suspendactionperformed (java.awt.event.ActionEvent evt) {                                        2         //  TODO Add Your handling code here:3             true;         4     }  

In this way, the execution of the fifothread thread can be paused and, accordingly, the Issuspend is assigned to false to continue execution.

It should be noted that this method is valid only if the thread needs to loop multiple times.

Methods for pausing and continuing other threads in the Java GUI

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.