Stopping a thread in an executor service
<p>I am faced with a situation where I need to stop a thread of Executor service from running.</p>

<p>I have already read the solution in other posts which says to make use of Future object and cancel the task.</p>

<p>But I rather tried a different approach.</p>

<p>Please can anyone let me know if there is any issue with this approach.</p>

<p>Following is my Runnable class.</p>

<pre><code>public class TestRunnable implements Runnable {     
    Thread t;
    @Override
    public void run() {
        // TODO Auto-generated method stub

        setT(Thread.currentThread());

        while(true)
        {
            if(Thread.currentThread().isInterrupted())
            {
                System.out.println("From Inside thread, Exiting");
                System.exit(0);
            }
        }
    }

    public void setT(Thread t) {
        this.t = t;
    }

    public Thread getT() {
        return t;
    }
}
</code></pre>

<p>Following is my main method:</p>

<pre><code>import java.io.IOException;    
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 

public class ruunTest {    
    public static void main(String[] args) throws IOException,     InterruptedException {    
        // TODO Auto-generated method stub    

        ExecutorService service = Executors.newCachedThreadPool();  

        TestRunnable test = new TestRunnable(); 

        service.execute(test);    

        Thread.sleep(1000);            
        System.out.println("About to Interrupt");     

        test.getT().interrupt();  
    }           
}
</code></pre>