黑马程序员技术交流社区

标题: java中通信初学 [打印本页]

作者: 陈文杰    时间: 2013-11-21 11:46
标题: java中通信初学
求解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
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at day20.ThreadNum.run(PrinNumChar.java:23)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at day20.ThreadChar.run(PrinNumChar.java:37)





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2