I think the choice of "static int c" is incorrect as it means that all instances of ThreadParam will "share" (and poorly at that) a common value for c. That is to stay, if you have 2 separate ThreadParams going simultaneously, one of them is likely present the "wrong" value for C. Consider...
class BadThreadParam implements Runnable {
static int c;
public BadThreadParam( int a, int b ) {
c = a + b;
}
public void run() {
System.out.println( c );
}
}
class ImmutableThreadParam implements Runnable {
private final int c;
public ImmutableThreadParam( int a, int b ) {
c = a + b;
}
public void run() {
System.out.println( c );
}
}
public class BadThreadParamTest {
public static void main( String[] args ) {
BadThreadParam shouldBe3 = new BadThreadParam( 1, 2 );
BadThreadParam shouldBe5 = new BadThreadParam( 3, 2 );
shouldBe3.run(); // Expect 3 but is 5. WTF?
shouldBe5.run(); // Expect 5.
ImmutableThreadParam expect3 = new ImmutableThreadParam( 1, 2 );
ImmutableThreadParam expect5 = new ImmutableThreadParam( 3, 2 );
expect3.run(); // Expect 3.
expect5.run(); // Expect 5.
}
}
If you make the "c" local to the instance, you overcome the "2 separate ThreadParams are affecting the same value" problem. If you make the "private int c" final, you are avoiding the need for synchronization. If you need to mutate "c" down in the run (or from the outside), now you are entering the world of synchronization...
class ThreadSafeMutableThreadParam implements Runnable {
private int c;
public ThreadSafeMutableThreadParam( int a, int b ) {
c = a + b;
}
public synchronized void setC( int c ) {
this.c = c;
}
public synchronized int getC() {
return c;
}
public void run() {
System.out.println( getC() );
}
}
Other than that, tuxdna's is correct in describing how you "pass params to a Runnable". The Runnable is inconsequential; you are passing params to a class (however you achieve that). If you need them available down in a run(), you need to be aware of synchronization.