Valhalla Legends Archive

Programming => General Programming => Java Programming => Topic started by: freedom on August 25, 2005, 01:37 AM

Title: how to do this ?
Post by: freedom on August 25, 2005, 01:37 AM
class MyThread extends Thread
{
static int counter=0;

public void run()
{
counter=counter+1;
System.out.println(counter); // is this correct if i create and run 10 threads ?

}

"static int counter" is a shared or class variable. so, do i need any synchronisation or lock to increment its values ?

if so, then how ?
Title: Re: how to do this ?
Post by: The-FooL on August 25, 2005, 07:35 AM
Why don't you just run it and see?  I believe you don't need any special synchronization.
Title: Re: how to do this ?
Post by: iago on August 25, 2005, 08:09 AM
I'm not sure how Java handles primitives in threads.  You should probably make it synchronized to be on the safe side, since it's not going to hurt anything. 
Title: Re: how to do this ?
Post by: freedom on August 25, 2005, 11:41 PM
Quote from: The-FooL on August 25, 2005, 07:35 AM
Why don't you just run it and see?  I believe you don't need any special synchronization.

i did that. at some point of time i got print   "3" ,"3","3".  three times i have got this 3 ... so that were not properly incremented.
Title: Re: how to do this ?
Post by: freedom on August 25, 2005, 11:42 PM
Quote from: iago on August 25, 2005, 08:09 AM
I'm not sure how Java handles primitives in threads.  You should probably make it synchronized to be on the safe side, since it's not going to hurt anything. 

how do i do that. will you please be kind enough to show that code ?
thank you
Title: Re: how to do this ?
Post by: iago on August 26, 2005, 08:39 AM
If I just tell you, you aren't going to learn. 

I suggest you look up "java synchronization" or "java thread synchronization" in Google.  The key word for synchronization, in Java, is "synchronized()". 

Title: Re: how to do this ?
Post by: gameschild on September 25, 2005, 09:03 PM
I believe you are looking for something like this:

public class C {

//static objects
static Object syncObj;
static int counter=0;

//static constructor
static {
syncObj = new Object();
}

//good 'ol main
public static void main(String[] args) {
C m = new C();
}

//std. constructor.
public C() {
MyThread m = new MyThread();
m.start();
}

//your counter class
public class MyThread extends Thread {
public void run() {
//syncronize on an object (or this) so it can only be accessed once
synchronized(syncObj) {
//print out the number (incremented by one of course)
System.out.println(counter++); // is this correct if i create and run 10 threads ?
}
}
}
}