A thread cannot be restarted during its life cycle so you can only create a new Thread instance.
Look at the following example, you should create your own thread class and define a flag for the control expire time of the loop.
public class InfiniteLoopThread implements Runnable {
private boolean flag = true;
public void surrender() {
this.flag = false;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
while (true) {
if (!this.flag) {
System.out.println(name + ": I am dead, do something....");
break;
}
System.out.println(name + ": I am alive, do something....");
}
}
public static void main(String[] args) throws InterruptedException {
InfiniteLoopThread jack = new InfiniteLoopThread();
InfiniteLoopThread mary = new InfiniteLoopThread();
Thread t1 = new Thread(jack);
Thread t2 = new Thread(mary);
t1.setName("Jack");
t2.setName("Mary");
t1.start();
t2.start();
Thread.sleep(500);
jack.surrender();
mary.surrender();
}
}
------------Outcome----------------
Jack: I am alive, do something....
Jack: I am alive, do something....
Jack: I am alive, do something....
Jack: I am alive, do something....
Jack: I am alive, do something....
Jack: I am alive, do something....
Mary: I am alive, do something....
Mary: I am alive, do something....
Jack: I am alive, do something....
Jack: I am dead, do something....
Mary: I am dead, do something....