Stop a thread with only one operation

I have a thread that runs a Runnable and looks like:

Runnable run = new Runnable() {
    @Override
    public void run() {
        functionCall();
    }

};
Thread thread = new Thread(run);
thread.start();

void functionCall() {
    for (int i=0; i<1000000; i++) System.out.println(i);
}

And I would like to stop it no matter what. I've tried with thread.interrupt() but I haven't been able to make it work because the functionCall() method doesn't really depends on me (I have no idea what's inside that function, this is only an example).

As far as I have seen, everyone uses a volatile boolean variable to check it but this thread is only executed ONCE so it's not really what I need.

Answers


Thread.interrupt() requires the thread being called on to yield control to the OS (for IO access, sleep etc.). So in order to use this you need to ensure that your thread does this (i.e. isn't solely computationally). See this JavaSpecialists entry for more information.


Need Your Help

RestKit automatically POST/PUT when back online

ios objective-c iphone swift restkit

Our app supports offline activity. Meaning we want to persist locally the creation of new core data objects as well as any modifications on existing objects. Then when the app goes online again we

simple onclick doesn't submit

javascript django twitter-bootstrap

I have found this great code snippets on this blog to change the language selector for something more stylish. (Twitter-bootstrap in mind)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.