執行緒併發庫(通訊,執行緒內共享資料)

2021-08-26 13:20:47 字數 2482 閱讀 7634

1.等待

在同步**中呼叫鎖物件的wait()方法,可以讓當前執行緒等待

2. 通知喚醒

使用鎖物件的notify()方法可以喚醒在該物件上等待的隨機乙個執行緒

使用鎖物件的notifyall()方法可以喚醒在該物件上等待的所有執行緒

示例:建立三個執行緒,其中乙個執行緒內部執行3次列印,第二個執行緒內部執行5次列印,第三個執行緒內部執行7次列印,如此交替執行10次。

public class notifytest 

}).start();

//執行緒二

new thread(new runnable()

}).start();

//執行緒三

new thread(new runnable()

}).start(); }}

class notifyservice catch (interruptedexception e)

} for (int i = 0; i < 3; i++)

system.out.println();

flag = 2; // 1結束後輪到2

this.notifyall(); // notify()喚醒隨機乙個, notifyall()喚醒所有

} public synchronized void print2(int j) catch (interruptedexception e)

} for (int i = 0; i < 5; i++)

system.out.println();

flag = 3;

this.notifyall(); }

public synchronized void print3(int j) catch (interruptedexception e)

} for (int i = 0; i < 7; i++)

system.out.println();

flag = 1;

this.notifyall();

}}

1.應用場景

在程式開發過程中我們經常需要在同乙個執行緒中共享資料,例如我們常見的銀行轉賬的案例,轉入和轉出是同乙個執行緒上執行的兩個方法,他們應該共享乙個事務物件。

2.解決方案

1) 自定義map

使用乙個key物件為thread型別的map用來儲存資料。

在儲存物件時將當前執行緒存為key,資料存為value。獲取物件時使用當前執行緒物件即可獲取到執行緒內部共享的資料。

採用map來儲存可能導致記憶體溢位

2) threadlocal

當呼叫其set()方法時會將資料和當前執行緒繫結,呼叫get()方法時則是獲取和當前執行緒繫結的資料。

private static mapmap = new hashmap();

public static void main(string args)

}).start();

new thread(new runnable()

}).start();

} private static class a

} private static class b

}

使用

// key值固定為thread的乙個map容器, 儲存物件的時候, 用當前執行緒作為key, 獲取的時候也是當前執行緒作為key

private static threadlocalthreadlocal = new threadlocal();

public static void main(string args)

}).start();

new thread(new runnable()

}).start();

} private static class a

} private static class b

}

使用

public static void main(string args) 

}).start();

new thread(new runnable()

}).start();

} private static class a

} private static class b }}

class shareddata

public static shareddata getshareddata()

return data;

} public string tostring()

public string getname()

public void setname(string name)

public int getage()

public void setage(int age)

執行緒併發庫(通訊,執行緒內共享資料)

1.等待 在同步 中呼叫鎖物件的wait 方法,可以讓當前執行緒等待 2.通知喚醒 使用鎖物件的notify 方法可以喚醒在該物件上等待的隨機乙個執行緒 使用鎖物件的notifyall 方法可以喚醒在該物件上等待的所有執行緒 示例 建立三個執行緒,其中乙個執行緒內部執行3次列印,第二個執行緒內部執行...

執行緒範圍內共享資料

我們可以先用所學知識來寫乙個 public class threadscopesharedata start static class a static class b 如果光像上面這樣寫的話,那毫無疑問,肯定是有問題的,如下圖所示並沒有實現執行緒共享 此時就實現執行緒內共享資料了 public c...

執行緒範圍內共享資料

假設現在有個公共的變數data,有不同的執行緒都可以去操作它,如果在不同的執行緒對data操作完成後再去取這個data,那麼肯定會出現執行緒間的資料混亂問題,因為a執行緒在取data資料前可能b執行緒又對其進行了修改,下面寫個程式來說明一下該問題 public class threadscopesh...