Question

In a Thread named a I have 2 loops, they both have to stop when flag is false. Somthing like that:

boolean flag = true;

t1 = new Thread(new Runnable()
{
    @Override
    public void run()
    {
        while(flag && another_condition)
        {
        }

        Do_something_that_takes_time

        while(flag && another_condition)
        {
        }

    });
}

Let's assume that we entered the first loop and in the middle of the loop run changed to false, now we will move to the "Do_somthing..." lane which might take few seconds to complete and then we will be moved to the second loop. In the meantime the value of flag might be changed once again to true! which means I will execute the second loop and I don't wish for that. So is that possible to do something like:

boolean flag = true;

t1 = new Thread(new Runnable()
{
    @Override
    public void run()
    {
        while(another_condition)
        {
            goto end;
        }

        Do_something_that_takes_time

        while(flag && another_condition)
        {
            goto end;
        }
        end:    
    });
}

The code I wrote now of course is not working but it's just to demonstrate my will. I know "break" should be the solution but I couldn't come up with a solution by using it.

Was it helpful?

Solution

If your goal is to break/exit from run method then you can just use return;.

OTHER TIPS

Put your while loops in methods, and after you exit the second loop/method, check if you need to call the first method again.

You could do something along these lines using break and another condition.

boolean flag = true;
boolean skip = false;

t1 = new Thread(new Runnable()
{
    @Override
    public void run()
    {
        while(another_condition)
        {
            skip = true;    
            break;
        }

        if (!skip) Do_something_that_takes_time;

        while(flag && another_condition && !skip)
        {
            break;
        }  
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top