Java線程通信在使用的時候需要我們不斷學習在學習的時候會有很多的問題存在其實我們在源代碼中就能發現其中的奧秘因為ThreadNum和ThreadChar都有對Objecto的引用所以你wait和notify的時候都應該同步Java線程通信具體看如下
public class Test {
public static void main(String[] args){
Object o=new Object();
Thread n=new ThreadNum(o);
Thread c=new ThreadChar(o);
nstart();
cstart();
}
}
class ThreadNum extends Thread{
Object o;
public ThreadNum(Object o){
thiso=o;
}
public void run(){
for(int i=;i<;i++){
Systemoutprintln(i);
Systemoutprintln(++i);
try {
synchronized (this) {
thiswait();
}
} catch (InterruptedException e) {}
synchronized (this) {
thisnotify();
}
}
}
}
class ThreadChar extends Thread{
Object o;
public ThreadChar(Object o){
thiso=o;
}
public void run(){
for(char a=A;a<=Z;a++){
Systemoutprintln(a);
synchronized (this) {
thisnotify();
}
try {
synchronized (this) {
thiswait();
}
} catch (InterruptedException e) {}
}
}
}
以上就是對Java線程通信的詳細介紹
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26955.html