如何为在Java中创建的可运行线程设置时间限制?
一次创建并运行多个线程。我怎么知道自创建每个线程以来的时间?
这是我使用的代码:
List<Thread> threads = new ArrayList<Thread>();
for(int i=0;i<no_of_threads;i++){
Runnable task = new MyRunnable(text,filename,prop,filename,L,L1,seq_no);
Thread worker = new Thread(task);
worker.start();
// Remember the thread for later usage
threads.add(worker);}
public class MyRunnable implements Runnable {
MyRunnable(String text,String filename,ArrayList<String> prop,String ip_file,Logger l,Logger l1,int seq_no) {
this.text=text;
this.filename=filename;
this.prop=prop;
this.ip_file=ip_file;
this.L=l;
this.L1=l1;
this.seq_no=seq_no;
}
@Override
public void run() {
/* other computation*/
}
答案 0 :(得分:1)
第二部分很简单 - 只需在MyRunnable中添加一个字段startTime
,就这样:
public class MyRunnable implements Runnable {
long startTime;
...
public void run() {
startTime = System.currentTimeMillis();
...
}
}
对于第一部分,限制运行时间,这有点棘手。你基本上需要设置一个计时器并手动终止线程来执行此操作。