how 2 threads communicate?
1 posts in topic
Flat View  Flat View

Posted By:   murali_krishna
Posted On:   Tuesday, August 29, 2006 06:54 AM

How two threads communicate with each other?

Re: how do 2 threads communicate?

Posted By:   Anonymous  
Posted On:   Tuesday, August 29, 2006 12:11 PM

Basically via memory i.e. member fields of a class. Any thread can write into a single field and let any other thread read its value.

But if you need to make sure that any value written into the field will also be found/read by another thread, you need to put the statements accessing your communication field into blocks

synchronized( lockObj ){ commField= ...; }

The lockObj is a central object (also called semaphore or mutex - for mutual exclusion ) you should choose carefully so that it can be accessed from all your classes and very early: think of an instance of java.lang.Class : that's a foolproof singleton.

I want to discourage you from using the "fast and easy" synchronized qualifier for methods. This way you end up with a mess of Locks and creating deadlocks!

Also have a look at the

Sun Java tutorial on Threads.

Kind regards,

About | Sitemap | Contact