在不同的类中创建对象的线程

时间:2017-07-07 06:01:50

标签: java multithreading

我正在尝试在这里学习线程。我有这个演示类打印第n个斐波纳契数。不,我试图在另一个类threadtest1中为这个演示对象创建一个线程并执行它。但我一直收到以下错误

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)

任何人都可以帮忙吗?

样本

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();
}
}

1 个答案:

答案 0 :(得分:1)

变化

demo d = new demo(l);

d = new demo(l);

因为你应该初始化字段,而不是创建局部变量

这样做会阻止

d.startDemo(t);

d未被初始化