Reputation:
I have this piece of code which is controlling two threads.
synchronized public void run() {
switch(ThreadChoice){
case 1:
dataBase();
break;
case 2:
ViewTotal.choice=1;new ViewTotal().displayDatabase();
break;
}
}
When i use SWITCH statement, it works fine but if i use if,if-else or if-else-if, it doesn't work correctly. Here is the code with if statement.
synchronized public void run() {
if(ThreadChoice==1)dataBase();
else if(ThreadChoice==2)ViewTotal.choice=1;new ViewTotal().displayDatabase();
}
while using the if case, it executes the code in both the conditions but while using the switch, it only executes the specified case. can anybody please elaborate this . i am much confused in it. Thanks in advance
Upvotes: 0
Views: 30
Reputation: 140504
This:
if(ThreadChoice==1)dataBase();
else if(ThreadChoice==2)ViewTotal.choice=1;new ViewTotal().displayDatabase();
is the same as:
if(ThreadChoice==1) {
dataBase();
} else if(ThreadChoice==2) {
ViewTotal.choice=1;
}
new ViewTotal().displayDatabase();
If you want the new ViewTotal().displayDatabase();
only to execute for ThreadChoice==2
, you need to use braces, and put it inside the appropriate brace:
if(ThreadChoice==1)dataBase();
else if(ThreadChoice==2) { ViewTotal.choice=1;new ViewTotal().displayDatabase(); }
But it's a reasonably good idea always to use braces, and to put one statement per line, so your intent is clear.
Upvotes: 3