您好,登錄后才能下訂單哦!
Java中怎么利用多線性同步讀寫數據,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
public class SynTest ...{
private String firstName, lastName;
private synchronized String getName() ...{
String result = firstName + " " + lastName;
return result;
}
private synchronized void setName(String firstName,
String lastName) ...{print("entering setName");
this.firstName = firstName;
print("Set first name have done firstName=" +
this.firstName);try ...{
Thread.sleep(1000);
} catch (InterruptedException e) ...{
}
this.lastName = lastName;
print("set last name have done,and leave setName()
method.firstName="+ this.firstName + " lastName=" + this.lastName);
}
private static void print(String msg) ...{
String thread = Thread.currentThread().getName();
System.out.println(thread + ": " + msg);
}
public static void main(String[] args) ...{
// 必需聲明為final,否則runnable里面的run()方法不能訪問。
final SynTest test1 = new SynTest();
// 設置初始值
test1.setName("arzu", "guli");
Runnable run1 = new Runnable() ...{
public void run() ...{
test1.setName("kang", "midi");
}
};
// 修改名字線程
Thread threadOne = new Thread(run1, "threadOne");
threadOne.start();
try ...{
Thread.sleep(200);
} catch (InterruptedException e) ...{
}
Runnable run2 = new Runnable() ...{
public void run() ...{
print("讀取" + test1.getName());
}
};
// 讀取名字線程
Thread threadTwo = new Thread(run2, "threadTwo");
threadTwo.start();
System.out.println("main() exit");
}
}
看完上述內容,你們掌握Java中怎么利用多線性同步讀寫數據的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。