How does Java stop a running thread?

Source: Internet
Author: User

A little bit of thread experience

First import the required packages

Improt Java.util.Timer;
Import Java.io.File;
Import Java.util.TimerTask;

You first need to create a thread and run it, and then create a timer task to trigger the event (such as creating a Stop.txt file that stops running the program if the file is found to exist).

public class stop{
public static void Main (String args[]) {

Create a thread, run it.
Count Cou=new count (true);
Thread th=new thread (COU);
Th.start ();

Create a Timer task
Timer time=new timer ();

Use the anonymous inner class to start the timing task, and if the file Stop.txt is found, stop the thread above.
Time.schedule (New TimerTask () {
public void Run () {
File File=new file ("Stop.txt");
if (file.exists ()) {
Count.setflag (FALSE);
System.exit (-1);
}
},100,1000);
}
}

Create a thread from the Runnable interface and create a Boolean flag variable to mark the running state.
Class Conunt implements runnable{
Private Boolean flag;
Public Count (Boolean flag) {
This.falg=flag;
}
public void Setflag (Boolean flag) {
This.falg=flag;
}

Override the abstract method of the Runnable interface to have the program output a thread-state number every second.
public void Run () {
for (int i=0;flag;i++) {
try{
Thread.Sleep (1000);
System.out.println (Thread.cuurentthread (). GetName () +i);
}catch{
SYSTEM.OUT.PRINTLN ("exception");
}

}
}

Personal experience, the lack of hope to point out.

How does Java stop a running thread?

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.