Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java break or exit from a thread

I have a thread that performs several different tasks. Each task is dependent on the previous one being successful.

If this were a method I might write (long hand) :

public boolean outerMethod()
{
    boolean success= performTask();

    if(success == false)
    {
        return false;
    } 

   // more processing here if success == true
}

and come out of the outerMethod back to the caller, and no further processing takes place

But...

If I am in the run() method of a thread and I do something like shown below...

How can I end the current thread there and then?

public void run()
{
    boolean success = performTask();

    if( success == false )
    {
        /* here is where I want to exit this thread */
    }   

    // further processing if success == true
}
like image 399
thonnor Avatar asked Oct 22 '14 13:10

thonnor


1 Answers

you can simply call return without a value to exit a void method earlier.

public void run() {
    boolean success = performTask();

    if( success == false ){
        return; //ends the thread
    }   
    // further processing if success == true
}
like image 92
Simulant Avatar answered Oct 01 '22 05:10

Simulant