1-If I run this code, It sometimes show two "ERROR" and sometimes one, Why?
Since you are spawning two threads Mrxaccount and Mrsxaccount, both may run at any time. In your main() method,
which implies that two objects Mrxaccount and Mrsxaccount will start two threads and will call run method at any time without knowing the sequence of execution.
Consider the scenario below:
Scenario 1:
Step 1: Suppose Mrxaccount object calls run() method at line no. 3. It will deduct 100 from amount. Value of total = 100-100 = 0
Step 2: Now Mrxaccount object starts
thread at line 1. It will call run method automatically which internally calls deduct() method. Since, total=0 here, 'else' statement will be executed and ERROR will be printed on screen.
Step 3: After printing ERROR, program will get terminated because of exit() method. So ERROR will be printed only one time.
Step 4: Remember here, other object Mrsxaccount didnt get turn to execute itself.
Scenario 2:
Step 1: Suppose, step 1 and 2 of scenario 1 is executed.
Step 2: Suppose, before the execution of Step 3, another object Mrsxaccount gets executed in the same manner Mrxaccount got executed till step 3. In that case, ERROR message will be printed by Mrsxaccount object and program termination will happen after that.
Here ERROR message you see will be twice.