Create two threads, one display odd & other even numbers

java, multithreading

Solution

I would just change a few details (no need to use the modulo operator here...):

public class Mythread {

    public static void main(String[] args) {
        Runnable r = new Runnable1();
        Thread t = new Thread(r);
        Runnable r2 = new Runnable2();
        Thread t2 = new Thread(r2);
        t.start();
        t2.start();
    }
}

class Runnable2 implements Runnable{
    public void run(){
        for(int i=0;i<11;i+=2) {
            System.out.println(i);
        }
    }
}

class Runnable1 implements Runnable{
    public void run(){
        for(int i=1;i<=11;i+=2) {
           System.out.println(i);
        }
    }
}

Problem

I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program? ``` public class Mythread { public static void main(String[] args) { Runnable r = new Runnable1(); Thread t = new Thread(r); t.start(); Runnable r2 = new Runnable2(); Thread t2 = new Thread(r2); t2.start(); } } class Runnable2 implements Runnable{ public void run(){ for(int i=0;i<11;i++){ if(i%2 == 1) System.out.println(i); } } } class Runnable1 implements Runnable{ public void run(){ for(int i=0;i<11;i++){ if(i%2 == 0) System.out.println(i); } } } ```

Original source

Related problems