-2

I am trying to learn threading here. I have this demo class which prints the nth fibonacci number. No I am trying to create a thread for this demo object in another class threadtest1 and execute it. but I keep getting the following error

Starting thread :Thread[Fibonacci thread,5,main]
Exception in thread "main" java.lang.NullPointerException
    at threadtest1.startThread(threadtest1.java:21)
    at threadtest1.main(threadtest1.java:27)

Can anyone help?

DEMO

class demo implements Runnable
{
private int limit;
public demo(int l)
{
    limit = l;
}
public demo()
{
    limit = 10;
}
public void startDemo(Thread t)
{
    t.start();
}
public void run()
{
    int c = 1;
    if(limit>2)
    {
        int i,a = 1,b = 1;
        for(i = 3;i<=limit;i++)
        {
            c = a+b;
            a = b;
            b = c;
        }
    }
    System.out.println("Fibonacci number["+limit+"] = "+c);
}
}

THREADTEST1

class threadtest1
{
private Thread t;
private demo d;
private int l;
public threadtest1(int l)
{
    this.l = l;
    demo d = new demo(l);
}
public threadtest1(int l1, int l2)
{
    this.l = (int)Math.max(l1,l2);
    demo d = new demo(l);
}

public void startThread()
{
    t = new Thread(d,"Fibonacci thread");
    System.out.println("Starting thread :" +t);
    d.startDemo(t);
}

public static void main(String args[])
{
    threadtest1 t1 = new threadtest1(5);
    t1.startThread();
}
}
VivekGhosh
  • 75
  • 1
  • 7

1 Answers1

1

change

demo d = new demo(l);

to

d = new demo(l);

as you should be initializing the field, not creating a local variable

doing so will prevent

d.startDemo(t);

d from being uninitialized

Scary Wombat
  • 41,782
  • 5
  • 32
  • 62