Synchronize thread and a method with an object?

I have a method and a thread which I’d like to run in the following order: First the method should do something with an object, and then the thread should do something with the object. They share the same object. I have to synchronize them, but I am just meeting with Threads. How can I do that?

private synchronized method()
{
//do something with an object (a field)
}

Runnable ObjectUpdater = new Runnable()
{
//do something with the object after the method has finished 
} 

My code, that somehow manages to freeze my Main thread (where the method is) My thread code:

private Runnable something = new Runnable(){
synchronized (this){
while (flag == false)
{ try {wait();)
catch (IntExc ie) {e.printStackTrace...}
}
//here it does its thing
}
setFlag(false);
}
My method code (part of the main thread)
private void Method()
{
//do its thing
setFlag(true); 
notifyAll();
}

Answer

To me that is simple questions

” you said that I do not know which is going to access the object first – the separate ObjectUpdater thread, or the main thread (with the method). If the separate thread accesses it before the main thread, that is bad and I don’t want this to happen”

if you want the main thread method to call first then the objectUpdater thread , have a flag to know whether the method is visited first by main thread ,if it is updater then call wait to this thread , once main finishes it call notify which will run separator thread, to know which thread is main thread or updater thread , set a name to the thread while creating it. and get the name as Thread.currentThread().getName().

Leave a Reply

Your email address will not be published. Required fields are marked *