I Want to execute a Certain Task to take only 1000 MS , if it exceeds , i dont want to continue with the task ,
i have used join for this .
Please tell me and guide me if this is correct or not
import java.util.List;
public class MainThread {
public static void main(String args[]) throws InterruptedException {
Thread mainthread = Thread.currentThread();
ChildThread child = new ChildThread();
Thread childThread = new Thread(child);
childThread.start();
mainthread.join(1000);
List list = child.getData();
if(list.size()<0)
{
System.out.println("No Data Found");
}
}
}
ChildTHread
import java.util.ArrayList;
import java.util.List;
public class ChildThread implements Runnable
{
List list = new ArrayList();
public List getData() {
return list;
}
public void run() {
// This List Data is feteched from Database currently i used some static data
list.add("one");
list.add("one2");
list.add("one3");
}
}
Nope. Incorrect. You do not need MainThread at all, you should call childThread.join(1000) instead.
But there is a problem with this approach as well – it will mean that the child thread will anyhow continue to be running.
Therefore you should call also childThread.interrupt() after join:
and in your child thread periodically in your childThread perform something like that:
and handle InterruptedException where needed – usually around any wait() methods you have.