在特定时间后停止线程 [英] Stop the thread after a particular time
问题描述
我想在特定时间后停止我的线程.在这里,我添加了我的示例代码.任何一个线程需要超过 6 秒意味着我想停止特定线程.线程的其余部分不应受到影响.我需要使用 Timer 还是我们可以实现的更好的方法?假设如果我使用 Timer 意味着我是否需要为每个线程创建新的计时器,如果作业在 6 秒之前完成,我是否需要取消计时器?
I want to stop my thread after particular time. Here with i added my sample code. Any one of the thread takes more than 6 seconds means i want to stop the particular thread. Rest of the thread should not be affected. Do i need to use the Timer or some better way can we achieve? Suppose if i used Timer means do i need to create new timer for each thread and do i need to cancel the timer suppose if the job finished before 6secs?
class MyRunnableThread implements Runnable{
public static int myCount = 0;
private String fname = null;
public MyRunnableThread(String fname){
this.fname = fname;
}
public void run() {
try{
//read the content based on text and peforms the operation
//File.read(this.fname)
System.out.println("Run method stuff"+ this.fname);
} catch (Exception iex) {
System.out.println("Exception in thread: "+iex.getMessage());
}
}
}
public class RunMyThread {
public static void main(String a[]){
System.out.println("Starting Main Thread...");
String[] fname = {"file1.txt","file2.txt","file3.txt","file4.txt","file5.txt"};
for(int i=0;i<5;i++){
try{
MyRunnableThread mrt = new MyRunnableThread(fname[i]);
Thread t = new Thread(mrt);
System.out.println("Main Thread start "+i);
t.start();
//stop the thread support run method takes more than 6seconds
System.out.println("Main Thread end "+ i );
} catch (Exception iex){
System.out.println("Exception in main thread: "+iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}
推荐答案
使用一个定时器和一个标志来告诉线程停止:
User a Timer and a flag to tell the thread to stop:
public class MyRunnableThread implements Runnable {
boolean run = true;
String fname;
public MyRunnableThread(String fname) {
this.fname = fname;
}
public void setRun(boolean toSet) {
run = false;
}
public void run() {
while (run) {
doStuff();
}
}
private void doStuff() {
// File.read(fname);
}
}
使用方法:
import java.util.Timer;
import java.util.TimerTask;
public class Tester {
public static void main(String args[]) {
String[] fname = { "file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt" };
for (int i = 0; i < 5; i++) {
try {
MyRunnableThread mrt = new MyRunnableThread(fname[i]);
Thread t = new Thread(mrt);
t.start();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int i = 6; // Time in seconds
public void run() {
System.out.println(i--);
if (i < 0) {
timer.cancel();
mrt.setRun(false);
}
}
}, 0, 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
将 i 更改为您想要的任何时间(以秒为单位)
Change i to whatever time in seconds you want
这篇关于在特定时间后停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!