兩個執行緒間的通訊
1、什麼時候需要通訊?
*多個執行緒併發執行時,在預設情況下cpu是隨機切換現成的;
*如果我們希望他們有規律的執行,就可以使用通訊,例如每個執行緒執行一次列印;
2、怎麼通訊?
*如果希望執行緒等待,就呼叫wait();
*如果希望喚醒等待的執行緒,就呼叫notify();
*這兩個方法必須在同步**塊中執行,並且使用同步鎖物件呼叫;
3、**示例如下:
package com.jh.www;
public
class
demo1
catch
(interruptedexception e)}}
}.start()
;new
thread()
catch
(interruptedexception e)}}
}.start()
;}}class
print
system.out.
print
("你");
system.out.
print
("好");
system.out.
print
("陌");
system.out.
print
("生");
system.out.
print
("人");
system.out.
print
("\r\n");
flag=2;
this
.notify()
;}}public
void
print2()
throws interruptedexception
system.out.
print
("我");
system.out.
print
("愛");
system.out.
print
("你");
system.out.
print
("北");
system.out.
print
("京");
system.out.
print
("\r\n");
flag=1;
this
.notify()
;}}}
第六章 多執行緒 設定以及獲取執行緒名稱
設定以及獲取執行緒名稱 1 用thread設定多執行緒中,設定並獲取執行緒名稱 package com.jh.www public class demo1 t.setname 灰太狼 t.start private static void demo start 2 runnable中設定並獲取執行緒...
第六章(4)終止執行緒的執行
終止執行緒的執行 若要終止執行緒的執行,可以使用下面的方法 執行緒函式返回 最好使用這種方法 通過呼叫 exitthread 函式,執行緒將自行撤消 最好不要使用這種方法 同乙個程序或另乙個程序中的執行緒呼叫 terminatethread 函式 應該避免使用這種方法 包含執行緒的程序終止執行 應該...
WIN32多執行緒程式設計學習筆記(第六章 下)
win32多執行緒程式設計學習筆記 第六章 下 收藏 繼續。上面的程式片段使用waitformultipleobjects函式來等待,會有兩個問題 第一 只能等待小於64個的物件,這是waitformultipleobjects函式本身所帶來的限制。第二 你必須不斷根據 哪乙個handle被激發 而...