[Solved] Java: How to print odd and even numbers from 2 separate threads using Executor framework

Introduction

The Executor framework in Java is a powerful tool for managing multiple threads. It allows you to easily create and manage threads, and to execute tasks in parallel. In this tutorial, we will learn how to use the Executor framework to print odd and even numbers from two separate threads. We will also discuss the advantages of using the Executor framework over traditional threading techniques. By the end of this tutorial, you will have a better understanding of how to use the Executor framework to manage multiple threads in Java.

Solution

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OddEvenExecutor {

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new OddNumberPrinter());
executorService.execute(new EvenNumberPrinter());
executorService.shutdown();
}
}

class OddNumberPrinter implements Runnable {

@Override
public void run() {
for (int i = 1; i <= 10; i += 2) { System.out.println("Odd Number: " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class EvenNumberPrinter implements Runnable { @Override public void run() { for (int i = 2; i <= 10; i += 2) { System.out.println("Even Number: " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }


Its a modified version of jasons:

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {

    public static void main(String[] args){
    final int max = 100;
    final AtomicInteger i = new AtomicInteger(0);
    Executor dd = Executors.newFixedThreadPool(2);

    final Object lock = new Object();

    dd.execute(new Runnable() {
        @Override
        public void run() {
            while (i.get() < max) {
                if (i.get() % 2 == 0) {
                    System.out.print(" " + i.getAndAdd(1));

                    synchronized(lock){
                        lock.notify();
                    }
                }else{
                    synchronized(lock){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    });
    dd.execute(new Runnable() {
        @Override
        public void run() {
            while (i.get() < max) {
                if (i.get() % 2 != 0) {
                    System.out.print(" " + i.getAndAdd(1));

                    synchronized(lock){
                        lock.notify();
                    }
                }else{
                    synchronized(lock){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    });
    do {
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } while (i.get() != max);
    System.out.println("\nDone");
}
}

Disclaimer: its not the best solution, and for sure not the fastest, but it produces the right output.

Thats the output:

 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
Done

0

solved Java: How to print odd and even numbers from 2 separate threads using Executor framework


How to Print Odd and Even Numbers from 2 Separate Threads Using Executor Framework in Java

Printing odd and even numbers from two separate threads is a common problem in Java. It can be solved using the Executor framework, which provides a convenient way to execute tasks in a thread pool. In this tutorial, we will learn how to use the Executor framework to print odd and even numbers from two separate threads.

What is the Executor Framework?

The Executor framework is a part of the Java concurrency API. It provides an easy way to execute tasks in a thread pool. The Executor framework simplifies the task of creating and managing threads. It also provides a convenient way to execute tasks in a thread pool.

How to Print Odd and Even Numbers from 2 Separate Threads Using Executor Framework?

To print odd and even numbers from two separate threads using the Executor framework, we need to create two tasks. The first task will print the odd numbers and the second task will print the even numbers. We can then submit these tasks to the Executor framework and it will execute them in a thread pool.

The following example shows how to print odd and even numbers from two separate threads using the Executor framework.

public class OddEvenExample {
 
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
 
        Runnable oddTask = () -> {
            for (int i = 1; i <= 10; i += 2) {
                System.out.println("Odd Number: " + i);
            }
        };
 
        Runnable evenTask = () -> {
            for (int i = 2; i <= 10; i += 2) {
                System.out.println("Even Number: " + i);
            }
        };
 
        executorService.submit(oddTask);
        executorService.submit(evenTask);
 
        executorService.shutdown();
    }
}

In the above example, we have created two tasks, one for printing odd numbers and one for printing even numbers. We have then submitted these tasks to the Executor framework and it will execute them in a thread pool. The output of the above program is as follows.

Odd Number: 1
Even Number: 2
Odd Number: 3
Even Number: 4
Odd Number: 5
Even Number: 6
Odd Number: 7
Even Number: 8
Odd Number: 9
Even Number: 10

As you can see, the Executor framework has executed the two tasks in a thread pool and printed the odd and even numbers from two separate threads.

Conclusion

In this tutorial, we have learned how to print odd and even numbers from two separate threads using the Executor framework in Java. The Executor framework simplifies the task of creating and managing threads and provides a convenient way to execute tasks in a thread pool.