Create two threads, one display odd & other even n

2020-02-08 05:57发布

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);
        }
    }
}

20条回答
SAY GOODBYE
2楼-- · 2020-02-08 06:43

Not the answer for the above problem but on the similar lines.

Program to print the elements of the array sequentially but use two different threads to print the adjacent elements

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ntv
 */
public class PrintLAternateNumber {
    public static void main(String[] args) {
        int [] num = {1,2,3,4,5,6};
        Printer p = new Printer();
        Thread t1 = new Thread(new Thread1(num,  p), "Thread1");
        Thread t2 = new Thread(new Thread2(num,  p), "Thread2");
        t1.start();
        t2.start();
    }


}

class Thread1 implements Runnable {
    int [] num;
    Printer p ;
    public Thread1(int[] num,  Printer p) {
        this.num = num;
        this.p = p;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void print() throws InterruptedException {
        int i = 1;

            while(i < num.length) {
                synchronized(num) {
                    while (p.evenPrinted) {
                        num.wait();
                     }
                }   

                synchronized(num) {
                     p.printEven(Thread.currentThread().getName(), num[i]);
                     i= i + 2;
                     num.notifyAll();

                }
            }
    }
}


class Thread2 implements Runnable {
    int [] num;
    Printer p ;
    public Thread2(int[] num, Printer p) {
        this.num = num;
        this.p = p;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void print() throws InterruptedException {
        int i = 0;

            while(i < num.length) {
                synchronized(num) {
                    while (!p.evenPrinted) {
                        num.wait();
                     }
                }    

                 synchronized(num) {
                     p.printOdd(Thread.currentThread().getName(), num[i]);
                     i = i + 2;
                     num.notifyAll();

                }
            }
    }
}

class Printer {
    boolean evenPrinted = true;
    void printEven(String threadName , int i) {
        System.out.println(threadName + "," + i);
        evenPrinted = true;
    }


        void printOdd(String threadName , int i) {
        System.out.println(threadName + "," + i);
        evenPrinted = false;
    }
}
查看更多
家丑人穷心不美
3楼-- · 2020-02-08 06:48
package javaapplication45;

public class JavaApplication45 extends Thread {

    public static void main(String[] args) {
        //even numbers
        Thread t1 = new Thread() {
            public void run() {
                for (int i = 1; i <= 20; i++) {
                    if (i % 2 == 0) {
                        System.out.println("even thread " + i);
                    }
                }
            }
        };
        t1.start();
        //odd numbers
        Thread t2 = new Thread() {
            public void run() {
                for (int i = 1; i <= 20; i++) {
                    if (i % 2 != 0) {
                        System.out.println("odd thread " + i);
                    }
                }
            }
        };
        t2.start();

    }

}
查看更多
老娘就宠你
4楼-- · 2020-02-08 06:49
package com.example;

public class MyClass  {
    static int mycount=0;
    static Thread t;
    static Thread t2;
    public static void main(String[] arg)
    {
        t2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " even \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>25)
                    System.exit(0);
                run();
            }
        });
        t=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " odd \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>26)
                    System.exit(0);
                run();
            }
        });
        t.start();
        t2.start();
    }
}
查看更多
叼着烟拽天下
5楼-- · 2020-02-08 06:49

public class ConsecutiveNumberPrint {

private static class NumberGenerator {

    public int MAX = 100;

    private volatile boolean evenNumberPrinted = true;

    public NumberGenerator(int max) {
        this.MAX = max;
    }

    public void printEvenNumber(int i) throws InterruptedException {
        synchronized (this) {
            if (evenNumberPrinted) {
                wait();
            }
            System.out.println("e = \t" + i);
            evenNumberPrinted = !evenNumberPrinted;
            notify();
        }
    }

    public void printOddNumber(int i) throws InterruptedException {
        synchronized (this) {
            if (!evenNumberPrinted) {
                wait();
            }
            System.out.println("o = \t" + i);
            evenNumberPrinted = !evenNumberPrinted;
            notify();
        }
    }

}

private static class EvenNumberGenerator implements Runnable {

    private NumberGenerator numberGenerator;

    public EvenNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i = 2; i <= numberGenerator.MAX; i+=2)
            try {
                numberGenerator.printEvenNumber(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

private static class OddNumberGenerator implements Runnable {

    private NumberGenerator numberGenerator;

    public OddNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i = 1; i <= numberGenerator.MAX; i+=2) {
            try {
                numberGenerator.printOddNumber(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public static void main(String[] args) {
    NumberGenerator numberGenerator = new NumberGenerator(100);
    EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(numberGenerator);
    OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(numberGenerator);
    new Thread(oddNumberGenerator).start();
    new Thread(evenNumberGenerator).start();

}

}

查看更多
Juvenile、少年°
6楼-- · 2020-02-08 06:50

The Question should be: Print Odd-Even Numbers simultaneously Using Threads

public class EvenOdd1 {
        static boolean flag = true;
        public static void main(String[] args) {
            Runnable odd = () -> {
                for (int i = 1; i <= 10;) {
                    if (EvenOddPrinter.flag) {
                        System.out.println(Thread.currentThread().getName() + " " + i);
                        i += 2;
                        EvenOddPrinter.flag = !EvenOddPrinter.flag;
                    }//if
                }//for
            };

            Runnable even = () -> {
                for (int i = 2; i <= 10;) {
                    if (!EvenOddPrinter.flag) {
                        System.out.println(Thread.currentThread().getName() + " " + i);
                        i += 2;
                        EvenOddPrinter.flag = !EvenOddPrinter.flag;
                    }
                }
            };

            Thread t1 = new Thread(odd, "Odd");
            Thread t2 = new Thread(even, "Even");
            t1.start();
            t2.start();
        }
    }
/*The output => 
Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Odd 9
Even 10
*/
查看更多
beautiful°
7楼-- · 2020-02-08 06:51

Nos will be printed in sequence

Main class
===========
package com.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class StartThread {
    static AtomicInteger no = new AtomicInteger(1);
    public static void main(String[] args) {
        Odd oddObj = new Odd();
        Thread odd = new Thread(oddObj);
        Thread even = new Thread(new Even(oddObj));
        odd.start();
        even.start();
    }
}

Odd Thread
===========
package com.thread;

public class Odd implements Runnable {

    @Override
    public void run() {
        while (StartThread.no.get() < 20) {
            synchronized (this) {
                System.out.println("Odd=>" + StartThread.no.get());
                StartThread.no.incrementAndGet();

                try {
                    this.notify();
                    if(StartThread.no.get() == 20)
                        break;
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

Even Thread
===========
package com.thread;

public class Even implements Runnable {
    Odd odd;

    public Even(Odd odd) {
        this.odd = odd;
    }

    @Override
    public void run() {
        while (StartThread.no.get() < 20) {
            synchronized (odd) {
                System.out.println("Even=>" + StartThread.no.get());
                StartThread.no.incrementAndGet();
                odd.notifyAll();
                try {
                    odd.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }       

    }

}

Output (Nos are printed in sequential)
======
Odd=>1
Even=>2
Odd=>3
Even=>4
Odd=>5
Even=>6
Odd=>7
Even=>8
Odd=>9
Even=>10
Odd=>11
Even=>12
Odd=>13
Even=>14
Odd=>15
Even=>16
Odd=>17
Even=>18
Odd=>19
查看更多
登录 后发表回答