Valhalla Legends Forums Archive | Java Programming | how to do this ?

AuthorMessageTime
freedom
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 ?
August 25, 2005, 6:37 AM
The-FooL
Why don't you just run it and see?  I believe you don't need any special synchronization.
August 25, 2005, 12:35 PM
iago
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. 
August 25, 2005, 1:09 PM
freedom
[quote author=The-FooL link=topic=12614.msg125377#msg125377 date=1124973308]
Why don't you just run it and see?  I believe you don't need any special synchronization.
[/quote]

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.
August 26, 2005, 4:41 AM
freedom
[quote author=iago link=topic=12614.msg125380#msg125380 date=1124975379]
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. 
[/quote]

how do i do that. will you please be kind enough to show that code ?
thank you
August 26, 2005, 4:42 AM
iago
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()". 

August 26, 2005, 1:39 PM
gameschild
I believe you are looking for something like this:
[code]
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 ?
}
}
}
}
[/code]
September 26, 2005, 2:03 AM

Search