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?