Sometimes we need to pause the main thread statements until the other thread completes. (Suppose if other thread produces/modifies the data to be used by main thread. If we do not pause the main thread statements in such case then main thread statements may use the data which is not modified/changed yet and an exception may occur)
If you use mainThread.sleep for this, you will have to mention time also. To overcome such situation, you can use an approach described below. The following steps leads to the solution:
|
Step 1 : Take a boolean variable isThreadComplete which should be accessible from your modifier thread also.
Step 2 : Set the isThreadComplete to false in main thread(normal execution) exactly before starting another thread(Modifier Thread).
Step 3 : After starting modifier thread, check the value of isThreadComplete. If it is false, do nothing. Along with this, In the last of modifier thread, set isThreadComplete to true.
The problem is solved. Let us see an example :
boolean isThreadComplete ;
Here are your main thread statements:
isThreadComplete = false;
MyThread t = new MyThread();
t.start;
while( ! isThreadComplete );
Here is your Modifier Thread which will reset the value of isThreadComplete after completion of its work:
class MyThread extends Thread
{
public void run()
{
…….
…….
…….
…….
isThreadComplete = true;
}
}
This approach can be applied to multiple threads also
|