Thread will be automatically cleaned up after the public void run()
method exits (implementation of which is your lambda expression), and there is no safe way you can explicitly tell the thread to stop.
However, you can simulate the stop
instruction, if you'll either introduce a shared flag variable, or simply create your thread by extending the Thread
class, instead of passing the Runnable
to the Thread constructor. This way you can incorporate a flag field:
class MyThread extends Thread {
private boolean isAlive;
public MyThread() {
this.isAlive = true;
}
public synchronized void setAlive(boolean status) {
if (status == true) {
return;
}
this.isAlive = status;
System.out.println("Stopping " + Thread.currentThread().getName() + "thread..");
System.out.println(Thread.currentThread().getName() + " has been stopped.");
}
@Override
public void run() {
int i = 0;
while (isAlive) {
System.out.println(i + " invocation in the " + Thread.currentThread().getName() + "thread.");
++i;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}
public class MainClass {
public static void main(String[] args) throws Exception {
MyThread thread = new MyThread();
thread.start(); //instruction #1
Thread.sleep(2000);
System.out.println("In the main thread...");
Thread.sleep(2000);
System.out.println("In the main thread...");
thread.setAlive(false); //after this, you'll see, that the Thread running after instruction #1 doesn't exist anymore
Thread.sleep(2000);
System.out.println("In the main thread...");
Thread.sleep(2000);
System.out.println("In the main thread...");
}
}