0

I am confused which way to use Run method

First One

new Thread(new Runnable() {
@Override
public void run() {
switch case //Here
}
}).start();

Second One

Switch(id){
case :
    new Thread(new Runnable() {
    @Override
    public void run() {

    }
    }).start();

break
}

which one is best to used in program.

5 Answers 5

2

It depends what you're trying to do. When you post something to a thread, it will run at some time in the future.

In your first case, your switch case statement will not run until your thread runs.

In the second case, your thread will not run unless your case statement is true.

They're just different logical flows, and I'm not sure which one can be considered "better".

0

I doesn't change much (if each case has a break statement, at least).

In each solution, only one case of the switch statement will be executed in a new thread. Use what you find the most readable.

Repeating the thread creation code in each case of the switch adds more boilerplate code. On the other hand, if you have a default case where nothing must be done, it's not worth creating and starting a new thread to do nothing.

0

The second case is best because thread will run only if your case condition true and it will not effects a lot to your application memory.

Too many threads in android application effects the memory.

0

Try this...

1. Run is the only method present in Runnable interface, and it must be implemented in the class which implements Runnable.

2. Now in your code you are using Anonymous class that implements Runnable interface.

3. In your 1st example, Your thread must run to make the switch case execute.

4. In your 2nd example, Your switch case's, particular case must execute to let the thread run.

0

What are the differences between the above two ??

First Problem: The thread runs, but the programming logic under a case may or may not run based on the case.

Second Problem: If & only If the case is true then the thread will run.

So its clear that the both scenario is totally different.

Which one will you use ??

Its depends on your requirements, use the logic what you need. Its solely depends on you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.