0

I'm working with threads in Java 8 and I'm using the next code:

 Runnable runnable = () -> {
            LOGGER.info(....);
           someCode
          };
    
          Thread thread = new Thread(runnable);
          thread.start();

My doubt is how can I stop or interrupt the thread or it will be stopped with itself?

Any ideas?

Michael
  • 41,989
  • 11
  • 82
  • 128
rasilvap
  • 1,771
  • 3
  • 31
  • 70

1 Answers1

0

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...");
    }
}
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66