我覺得「靜INT C」的選擇是不正確的,這意味着所有實例ThreadParam將「共享」(並且很差),爲c的共同值。這是留,如果你有2個獨立的ThreadParams同時去,其中一人可能是本作C.「錯誤」的價值考慮...
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.
}
}
如果使「C」本地實例,你克服了「2個獨立的ThreadParams影響相同的價值」的問題。如果您最終創建了「private int c」,那麼您就避免了同步的需要。如果您需要變異「C」向下運行(或從外),你現在進入同步的世界......
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());
}
}
除此之外,tuxdna的是正確的描述你怎麼「通params to Runnable「。 Runnable是無關緊要的;你將params傳遞給一個類(但是你實現了這個)。如果您需要在運行()中使用它們,則需要了解同步。
你在方法ThreadParam – Vorsprung