使用stop()釋放鎖給資料造成的不一致的結果——T1117
阿新 • • 發佈:2021-01-13
package 多執行緒技能1;
/**
* 使用stop()釋放鎖給資料造成的不一致的結果
* 對鎖定的物件進行“解鎖”操作,會導致資料得不到同步的處理,進而
* 出現數據不一致的問題。
*/
/**
* 測試
*/
class MyServer1R1117 extends Thread{
private String username="a";
private String password ="aa";
synchronized public String getUsername (){
return username;
}
synchronized public String getPassword(){
return password;
}
synchronized public void printString(String username,String password){
try {
this.username=username;
Thread.sleep(100000);
this.password=password;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 呼叫printString()
*/
class MyThreadA extends Thread{
private MyServer1R1117 object;
public MyThreadA(MyServer1R1117 object){
super();
this.object=object;
}
@Override
public void run() {
object.printString("b","bb");
}
}
/**
* 輸出username 和 password
*/
class MyThreadB extends Thread{
private MyServer1R1117 object;
public MyThreadB (MyServer1R1117 object){
super();
this.object=object;
}
@Override
public void run() {
System.out.println("username="+object.getUsername());
System.out.println("password="+object.getPassword());
}
}
/**
* 測試類
*/
class RunT1117{
public RunT1117(){
try {
MyServer1R1117 object=new MyServer1R1117();
MyThreadA threadA=new MyThreadA(object);
threadA.start();
Thread.sleep(100);
MyThreadB myThreadB=new MyThreadB(object);
myThreadB.start();
Thread.sleep(3000);
threadA.stop();
System.out.println("stop()執行後,在下方開始列印username和password");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class T1117 {
public static void main(String[] args) {
RunT1117 runT1117=new RunT1117();
}
}