在下面的例子併發執行靜態和非靜態同步方法的問題?
- 如果不同的線程試圖同時訪問靜態和 非靜態同步方法,進而嘗試 改變使用兩種方法中的靜態數據會發生什麼?
- 使用run()方法的do-while循環到 是否有任何問題爲每個非靜態的 同步方法調用創建類BadDesign的新對象?
- 此Java代碼是否正確同步?
下面是示例代碼說明我的問題:
BadDesign.java
public final class BadDesign{
private static int sensitiveData;
public synchronized static void changeDataViaStaticMethod(int a){
//... updating the sensitiveData
sensitiveData = a;
}
public synchronized void changeDataViaNonStaticMethod(int b){
//... updating the sensitiveData
sensitiveData = b;
}
public static void showSensitiveDataStatic(){
System.out.println("Static: " + Thread.currentThread().getName()+ " - " + sensitiveData);
}
public void showSensitiveData(){
System.out.println(Thread.currentThread().getName() + " - " + sensitiveData);
}
public static void main(String[] args){
new Thread(new TestThread11()).start();
new Thread(new TestThread11()).start();
}
}
而且TestThread11.java
class TestThread11 implements Runnable{
public void run(){
int i = 0;
do{
BadDesign.changeDataViaStaticMethod(5);
BadDesign.showSensitiveDataStatic();
//... new object for every iteration
//... so synchronization of non-static method
//... doesn't really do anything significant here
BadDesign bd = new BadDesign();
bd.changeDataViaNonStaticMethod(10);
bd.showSensitiveData();
}while (i++ < 100);
}
}
我很累,很早在早上編輯一篇文章。我會讓其他敏銳的編輯出現並佔據這個堡壘。 ;-) –
@The精英紳士 - 你們不睡覺:P。考慮編輯它。 – Perception