Java中线程通信简单问题,急需解决

来源:百度知道 编辑:UC知道 时间:2024/06/21 05:16:58
public class PrinNumChar {
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=1;i<26;i++){
System.out.println(i);
System.out.println(++i);
try {
this.wait();
} catch (InterruptedException e) {}
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);
this.notify();
try {
this.wait();
} catch (InterruptedException e) {}
}
}
}

这个程序的运行结果是:
1
2
A
Exce

因为ThreadNum和ThreadChar都有对Object o的引用,所以你wait和notify的时候都应该同步,具体看如下

public class Test8 {
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=1;i<26;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