1

我只是想在java中调用一个线程。我想检查线程是否被中断。线程在“调度程序”类中定义。这是代码:

        if (flag == true) 
        {
        thread = new Scheduler();
        thread.start();
        } 

        else 
        {
        thread.interrupt();
        }

        public void run() 
        {
            while (thread.isInterrupted() != true) // Here i get a NPE...
           { 
             //....
           }
        }
4

3 回答 3

1

你得到的原因NullPointerException可能是因为该变量没有初始化,因为flag在声明中是错误的if,但我认为这不是问题的根源。

如果你想检查被调用的线程是否被中断,你应该使用

while (!this.isInterrupted()) {

在您的代码段中,您似乎正在测试另一个Scheduler对象。

于 2013-05-14T12:42:57.790 回答
1

首先,由于 flag 是一个布尔值,您可以简单地编写:

  if (flag) 
    {
        thread = new Scheduler();
        thread.start();
    } 

 else 
    {
        thread.interrupt();
    }

我相信你的问题是标志评估为假,你最终调用isInterrupted()了一个空对象。您也很可能指的是与您认为的完全不同的线程。目前尚不清楚您指的是哪个对象-您需要发布更多代码。

还:

while (!thread.isInterrupted()) // isInterrupted() returns a boolean, you don't need != true
   { 
             //....
   }
于 2013-05-14T12:45:01.983 回答
0

is the run() code snippet from your Scheduler ? In the run why do you have thread.isInterrupted() ? instead use

Thread.currentThread().isInterrupted()

Also would be good to see the constructor and where the thread variable is declared

于 2013-05-14T13:05:37.587 回答