我有以下的類,它應該是線程安全的:線程安全的引用類型,而無需使用同步
public class ShouldBeMadeThreadSafe {
private double[] k = {70.0,70.0};
private double[] b = {10.0,10.0};
private double[] m = {5.0,6.0};
public synchronized void setKX(double kx) {k[0]=kx;}
public synchronized void setKY(double ky) {k[1]=ky;}
public synchronized void setBX(double bx) {b[0]=bx;}
public synchronized void setBY(double by) {b[1]=by;}
public synchronized void setMX(double mx) {m[0]=mx;}
public synchronized void setMY(double my) {m[1]=my;}
public double[] getK() {return Arrays.copyOf(k, k.length);}
public double[] getB() {return Arrays.copyOf(b, b.length);}
public double[] getM() {return Arrays.copyOf(m, m.length);}
}
這當然有在干將知名度的問題,因爲之前發生關係只在顯示器的解鎖和鎖定之間保證。
明顯的解決將是synchronized關鍵字添加到干將:
public class OkButIDontLikeDeadlocks {
private double[] k = {70.0,70.0};
private double[] b = {10.0,10.0};
private double[] m = {5.0,6.0};
public synchronized void setKX(double kx) {k[0]=kx;}
public synchronized void setKY(double ky) {k[1]=ky;}
public synchronized void setBX(double bx) {b[0]=bx;}
public synchronized void setBY(double by) {b[1]=by;}
public synchronized void setMX(double mx) {m[0]=mx;}
public synchronized void setMY(double my) {m[1]=my;}
public synchronized double[] getK() {return Arrays.copyOf(k, k.length);}
public synchronized double[] getB() {return Arrays.copyOf(b, b.length);}
public synchronized double[] getM() {return Arrays.copyOf(m, m.length);}
}
我不是這一個迷,因爲這樣我調用了鎖外星人方法舉行,這正在尋求可能的僵局。也許這不是這種情況,但即使如此,我認爲它不夠優雅(如果我錯了,請糾正我)。
現在我在想,如果下面是線程安全的:
public class AmIThreadSafe {
private volatile double[] k = {70.0,70.0};
private volatile double[] b = {10.0,10.0};
private volatile double[] m = {5.0,6.0};
public void setKX(double kx) {k[0]=kx;}
public void setKY(double ky) {k[1]=ky;}
public void setBX(double bx) {b[0]=bx;}
public void setBY(double by) {b[1]=by;}
public void setMX(double mx) {m[0]=mx;}
public void setMY(double my) {m[1]=my;}
public double[] getK() {return Arrays.copyOf(k, k.length);}
public double[] getB() {return Arrays.copyOf(b, b.length);}
public double[] getM() {return Arrays.copyOf(m, m.length);}
}
我不認爲這是因爲我沒有改寫揮發性引用本身。
那麼,使ShouldBeMadeThreadSafe線程安全的最好方法是什麼?
我接受了這個答案,因爲它側重於我提出這個問題的原因,這是對「外星代碼」的含義的誤解。 – deinocheirus