使用多线程打印奇数和偶数

时间:2018-10-22 10:51:09

标签: java multithreading synchronization java-threads thread-synchronization

我对线程还很陌生,只是想掌握一些基础知识。因此,我尝试了以下代码来依次打印奇数和偶数。

但是我得到一个空指针。

公共类P {

public static void main(String[] args) throws InterruptedException {

     Print print = new Print(false);
     Even e =new Even();
     Odd o = new Odd();  
     e.start();
     o.start();
}

}

class甚至扩展线程 {     打印打印;

public void run()
{
  try {
    print.printeven();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

}

class Odd扩展线程 {     打印打印;

public void run()
{
  try {
    print.printodd();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

}

类打印{

public  boolean flag=false;

Print(boolean flag){

    this.flag=flag;
}

synchronized void printodd() throws InterruptedException
   {

    for(int i=1;i<10;i=i+2)
        if(!flag)
        {
        System.out.println(i);
        notifyAll();
        flag=true;
        }
        else
        {
            wait();
        }
   }

synchronized void printeven() throws InterruptedException
   {

    for(int i=2;i<=10;i=i+2)
        if(flag)
        {
        System.out.println(i);
        notifyAll();
        flag=false;
        }
        else
        {
            wait();
        }
   }

}

如果有人可以在这里详细解释我在做什么错,并给出了基本的调试方法。

2 个答案:

答案 0 :(得分:0)

您尚未在ODD和EVEN类中实例化Print实例。

对偶数和奇数构造函数都执行此操作。

public Odd(Print print) 
{ 
  this.print = print;
}

实例化时要这样做。

 Print print = new Print(false);
 Even e =new Even(print);
 Odd o = new Odd(print);  

答案 1 :(得分:0)

看到你无所事事

Print print = new Print(false); // this statement

在main()方法中。

将“打印”对象传递给Odd和Even类的Constructor。

您将获得Null指针,因为您没有初始化打印对象奇数和偶数类。

相关问题