Reg: Counter Variable in Thread
I have a requirement that should assign a counter variable for each thread that gets invoked. But I am not getting the expected results, actually the counter is duplicating in the threads. I created a dummy table and a proc to insert the counter value into the table. Is there anyway that the code can be changed so that the thread gets an incremented value.
In the below code, the variable counter
is a static int
public synchronized int testSequence(){
System.out.println("testSequence::::: "+counter++);
//Random rn = new Random();
CallableStatement cstmt;
{
try {
cstmt = conn.prepareCall("{call insertjtest(?)}");
cstmt.setInt(1,counter);
//cstmt.setInt(1, rn.nextInt());
cstmt.execute();
cstmt.close();
c开发者_高级运维onn.commit();
return counter;
} catch (SQLException e) {
// TODO Auto-generated catch block
return 0;
}
}
}
But I find the
If I understood your question correctly, you want to increment the variable counter
on each invocation of the thread (or its run-method).
Thus, you could try something like:
Thread myThread = new Thread(myRunnable) {
private int myValue;
public void run() {
// Call your "routine" ..
myValue = XXX.testSequence();
super.run();
}
};
I think you can just add volatile to your counter
if you want :
- independent couters for each thread, you can use a ThreadLocal variable or an instance variable for each Thread object
- a counter for all threads, you can use an AtomicInteger variable
EDIT : After having seen your code, it is one counter for all threads, so you can use an AtomicInteger for all and it is not necessary to be synchronized because AtomicInteger is a multithreaded object.
You likely want to make your counter value either volatile, or an AtomicInt - it's not guaranteed in Java that multiple threads will immediately see updates to variables.
精彩评论