Multi-Threading : Running Two threads

By | August 6, 2017

This is a simple example of threads in java.

Threads in Java belong to the category of multi-threading.A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.

We are giving you an example of a basic example of threads here.

This example has two threads, such that one of the thread print even no‘s and another print odd no‘s up to a given range.

 

public class P3 {
    public static void odd() {
        for (int i = 1; i < 20; i= i+ 2) {
            System.out.print(i + " ");   // printing odd numbers
        }
        System.out.println(); // TO break the line
    }

    public static void even() {
        try {
            Thread.sleep(300); // thread on sleep for 300 millisecond
        } catch (InterruptedException e)   // If there is any error it will show exception
        {
            System.out.println(e);
        }

        for (int i = 0; i < 21; i = i + 2) {
            System.out.print(i + " ");   //printing even numbers
        }

    }

    public static void main(String[] args) {
        //separately executing thread first odd will execute then even
        Thread oddstart= new Thread(()->odd());
        Thread evenstart= new Thread(()->even());
        oddstart.start();
        evenstart.start();

    }
}

Output

1 3 5 7 9 11 13 15 17 19 
0 2 4 6 8 10 12 14 16 18 20