Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我的线程在同一时间运行,导致它们的输出混合在一起,因此我在第一个线程上设置了延迟,但是由于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();
        }
    }
}

最佳答案

引发异常时需要new关键字

throw new InterruptedException("...");


但是sleep会抛出自己的InterruptedException,因此无需显式抛出异常

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


读取:Pausing Execution with Sleep

关于java - 使用throw InterruptedException时出现“找不到符号”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23506028/

10-09 02:59