Question

My threads were running at the same time, causing their outputs to be mixed up, so I put a delay on the first thread and yet I cannot get it to run because Java refuses to accept InterruptedException. Below is my code so far:

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();
        }       
    }
}
Was it helpful?

Solution

The new keyword is needed when throwing an exception

throw new InterruptedException("...");

but sleep will throw its own InterruptedException so there's no need to throw the exception explicitly

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

Read: Pausing Execution with Sleep

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top