使用throw InterruptedException时“找不到符号”

时间:2014-05-06 23:08:56

标签: java multithreading interrupted-exception

我的线程同时运行,导致它们的输出混淆,所以我在第一个线程上放了一个延迟,但我无法让它运行,因为Java拒绝接受InterruptedException。以下是我目前的代码:

class Evens extends Thread
{
    public void run()
    {
        System.out.println("");
        System.out.println("Even numbers between 0 and 30:");
        System.out.println("");
        boolean isEven;
        for (int num = 0; num <=30; num++)  //This for loop tests for evenness and then prints it.
        {
            if(num % 2 == 0)
            {
                    isEven = true;
        }
            else
            {
                isEven = false;
        }

            if(isEven == true)
            {
                System.out.print(num + ", ");
            }
            else
            {
            }
        }
    }
}

class Odds extends Thread
{
    public void run()
    {
        System.out.println("");
        System.out.println("Odd numbers between 0 and 30:");
        System.out.println("");
        boolean isOdd;
        for (int num = 0; num < 30; num++)  //This for loop tests for oddness and then prints it.
        {
            if(num % 2 != 0)
            {
                isOdd = true;
            }
            else
            {
                isOdd = false;
            }

            if(isOdd == true)
            {
                System.out.print(num + ", ");
            }
            else
            {
            }
        }
    }
}    

class Printer
{    
    public static void main(String args[])
    {
        Evens ev = new Evens();
        Odds od = new Odds();
        throw InterruptedException("Another string is running!");
        {
            ev.start();
            Thread.sleep (4000);
            od.start();
        }       
    }
}

1 个答案:

答案 0 :(得分:0)

抛出异常时需要new关键字

throw new InterruptedException("...");

sleep会抛出自己的InterruptedException,因此无需明确抛出异常

try {
    Thread.sleep (4000);
} catch (InterruptedException e) {
   ...
}

阅读:Pausing Execution with Sleep