• Welcome to Valhalla Legends Archive.
 

how to do this ?

Started by freedom, August 25, 2005, 01:37 AM

Previous topic - Next topic

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 ?

The-FooL

Why don't you just run it and see?  I believe you don't need any special synchronization.

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. 
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


freedom

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.

freedom

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

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()". 

This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


gameschild

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 ?
}
}
}
}