在java中设置可运行线程的时间限制?
如何为Java中创建的可运行线程设置时间限制 一次创建并运行多个线程。如何知道每个线程自创建以来的时间 这是我使用的代码:在java中设置可运行线程的时间限制?,java,multithreading,runnable,Java,Multithreading,Runnable,如何为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
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*/
}
List threads=new ArrayList();
对于(int i=0;i第二部分很简单-只需在MyRunnable中添加一个字段startTime
,如下所示:
public class MyRunnable implements Runnable {
long startTime;
...
public void run() {
startTime = System.currentTimeMillis();
...
}
}
对于第一部分,限制运行时间,这有点棘手。您基本上需要设置一个计时器并手动终止线程来完成此操作。当您的runnable开始运行时,将开始时间设置为当前时间。在其代码中,定期检查当前时间是否低于添加到开始时间的限制,然后停止runn如果是这样的话,则正在加载。这可能很有用。@jbniset:不可能定期检查时间,因为:1.系统涉及大量计算,分配内存用于检查时间是不可行的。2.创建更多线程时,总体性能会降低。system.currentTimeMillis()/system.nanoTime()不需要太多内存,而且可能足够快。无论如何,没有其他安全的解决方案。没有线程的合作,线程无法停止。要进行合作,线程必须检查条件。您可以使用计时器中断线程,但被中断的线程必须定期检查中断状态,以知道何时停止p、 除了在runnable方法中计算线程的创建时间外,是否还有其他方法可以知道线程的创建时间?