Thread synchronization
From: Razvan (mihai11_at_mailcity.com)
Date: 08/31/04
- Next message: James Robert Leek: "JNI Invocation: static UN-initializers?"
- Previous message: Babu Kalakrishnan: "Re: Java exceptions and function overriding."
- Next in thread: Eric Sosman: "Re: Thread synchronization"
- Reply: Eric Sosman: "Re: Thread synchronization"
- Reply: xarax: "Re: Thread synchronization"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 31 Aug 2004 09:13:48 -0700
Hi
Is the following code correct ?
public class CDummy2 extends Thread
{
Integer threadId;
CDummy2(Integer threadId) { this.threadId = threadId;}
public static void main(String args[])
{
System.out.println("CDummy2.");
CDummy2 cd1 = new CDummy2(new Integer(1));
CDummy2 cd2 = new CDummy2(new Integer(2));
System.out.println("Starting thread 1...");
cd1.start();
try {
Thread.sleep(250);
}
catch(InterruptedException ee) {
System.out.println("The thread was interrupted !");
}
System.out.println("Starting thread 2...");
cd2.start();
}
public void run()
{
int ii = 50;
while(ii-- > 0)
{
printData("threadId: " + threadId + ", ii=" + ii);
try {
Thread.sleep(100);
}
catch(InterruptedException ee) {
System.out.println("The thread was interrupted !");
}
}
}
void printData(String input) {
synchronized (threadId) {
System.out.println(input);
}
}
}
I am synchronizing 2 threads on the Integer 'threadId'. Since the
code is trivial it seems to work. However, each thread class has its
own threadId. Since the object is not common for the 2 threads, that
means no synchronization is taking place in the method printData().
The only solution that I can think of is to make the threadId static.
Being static all the threads will share the same static object thus
synchronization should occur.
If my observation is correct that means that you can only synchronize
on class (static) variables but not on member variables.
My head is spinning. I am thinking to this for over 1 hour. There
should be a very simple explanation.
Regards,
Razvan
- Next message: James Robert Leek: "JNI Invocation: static UN-initializers?"
- Previous message: Babu Kalakrishnan: "Re: Java exceptions and function overriding."
- Next in thread: Eric Sosman: "Re: Thread synchronization"
- Reply: Eric Sosman: "Re: Thread synchronization"
- Reply: xarax: "Re: Thread synchronization"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|