Here goes the code
public class MyThread implements Runnable {
private boolean stop;
@Override
public void run() {
System.out.println("Thread starts");
while(!stop) {
try {
//do something fooBar()
System.out.println("Sleeping...");
Thread.sleep(5000);
} catch(InterruptedException e) {
System.out.println("Thread was inturrupted");
} catch(Exception e) {
//handle error
e.printStackTrace();
}
}
System.out.println("Thread ends");
}
public void setStop(boolean stop) {
this.stop = stop;
}
public static void main(String args[]) throws InterruptedException {
MyThread m = new MyThread();
Thread t = new Thread(m);
t.start();
System.out.println("Main thread Sleeping...");
Thread.sleep(2000);
//stop in this manner
m.setStop(true);
t.interrupt();
}
}