> If I use the keyword synchronized on the Display1 method then this
> works fine and not the outputs get interupted by the other Display1
> threads, likewise with Display2. But is there are way that just
> these two particular methods can also not interrupt each other
> aswell? At the moment they are giving me mixed up output from the
> two seperate methods.
Instead of declaring the method synchronized, wrap the method body in
a synchronized block where you specify what object to synchronize on,
e.g.:
public void display() {
synchronized (obj) {
// do something here
}
}
Every block of code that synchronizes this way *and* specifies the
*same* obj will be mutually exclusive.
As was recommended elsewhere in this thread, I suggest you get
yourself a copy of Doug Lea's Concurrent Programming in Java.
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Mr B wrote On 03/14/07 11:38,:
> In my application I have two methods which can be run by an infinite
> number of threads,
Impressive. How long does it take to start them all?
> the operation of the method is to output an array
> of contents one line at a time. If I use the keyword synchronized on
[quoted text clipped - 3 lines]
> interrupt each other aswell? At the moment they are giving me mixed
> up output from the two seperate methods.
Synchronize on the same object. When you write
`synchronized' at the start of a method or block of code,
it means `synchronized(this)' or `synchronized(theClassObj)'
for a static method. If Display1 and Display2 synchronize
on different objects, nothing prevents them from running
at the same time.

Signature
Eric.Sosman@sun.com
Ashoka! - 15 Mar 2007 04:17 GMT
> Mr B wrote On 03/14/07 11:38,:
>
[quoted text clipped - 20 lines]
> --
> Eric.Sos...@sun.com
Just to add instead of adding synchronized key word to the method use
void Display1(Object x, any other parameters)
{
Synchronize(x)
{
//code goes here
}
}
void Display2(Object x, any other parameters)
{
Synchronize(x)
{
//code goes here
}
}
where x is any object but both functions must get same instance of x
e.g.
void main()
{
String lock = "This is the common lock";
display1(lock);//obvously these two calls are synchronus but you get
my point of same instance right?
display2(lock);
}
also look at the sempahore class for much better control of multiple
threads.
I hope this helps,
Usman