()奥秘 Java线程通信源代码中的奥秘探究
Java线程通信源代码中的奥秘探究
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);
n start();
c start();
}

}
class ThreadNum extends Thread{
Object o;
public ThreadNum(Object o){
this o=o;
}
public void run(){
for(int i= ;i< ;i++){
System out println(i);
System out println(++i);
try {
synchronized (this) {
this wait();
}
} catch (InterruptedException e) {}
synchronized (this) {
this notify();
}
}
}
}
class ThreadChar extends Thread{
Object o;
public ThreadChar(Object o){
this o=o;
}
public void run(){
for(char a= A ;a<= Z ;a++){
System out println(a);
synchronized (this) {
this notify();
}
try {
synchronized (this) {
this wait();
}
} catch (InterruptedException e) {}
}
}
}
lishixinzhi/Article/program/Java/hx/201311/26955