java允許多線程并發控制,當多個線程同時操作一個可共享的資源變量時(如數據的增刪改查), 將會導致數據不準確,相互之間產生沖突,因此加入同步鎖以避免在該線程沒有完成操作之前,被其他線程的調用,從而保證了該變量的唯一性和準確性。
我們來看java中第二種同步的方式,使用同步方法。
/**
* 線程間通訊,多個線程處理同一個資源,但是任務不一樣
* @author xj
*
*/
/*
* 定義資源
*/
class Resource2{
String name;
String sex;
Boolean flag = false;
public synchronized void set(String name, String sex){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.sex = sex;
flag = true;
notify();
}
public synchronized void out(){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name + " : " + this.sex);
flag = false;
notify();
}
}
/*
* input 輸入操作
*/
class Input2 implements Runnable{
private Resource2 r;
public Input2(Resource2 r) {
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x == 0){
r.set("zhangsan", "男");
}
else {
r.set("Lisi", "女");
}
x = (x + 1)%2;
}
}
}
/**
* 輸出
* @author xj
*
*/
class Output2 implements Runnable{
Resource2 r;
public Output2(Resource2 r) {
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
public class ResourceDemon02 {
public static void main(String[] args) {
// 創建資源
Resource2 r = new Resource2();
// 創建任務
Input2 in = new Input2(r);
Output2 out = new Output2(r);
//創建線程,執行路徑
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//線程啟動
t1.start();
t2.start();
}
}