Java code to run multiple threads in a program

Java thread example: Here, we are going to learn how to run multiple threads in a program in java programming language?
Submitted by IncludeHelp, on July 14, 2019

The task is to execute / run multiple threads in a program in java.

In the below code, we are creating a static method printNumbers() to print numbers from 1 to 10, creating two threads one and two, and initializing them with the method using Main::printNumbers.

Code:

public class Main {
    //method to print numbers from 1 to 10
    public static void printNumbers() {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        //printing new line
        System.out.println();
    }

    //main code	
    public static void main(String[] args) {
        //thread object creation
        Thread one = new Thread(Main::printNumbers);
        Thread two = new Thread(Main::printNumbers);

        //starting the threads
        one.start();
        two.start();
    }
}

Output

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Initializing threads with different methods

public class Main {
    //method1 - printing numbers from 1 to 10
    public static void printNumbers1() {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        //printing new line
        System.out.println();
    }

    //method2 - printing numbers from 10 to 1
    public static void printNumbers2() {
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        //printing new line
        System.out.println();
    }	

    //main code	
    public static void main(String[] args) {
        //thread object creation
        Thread one = new Thread(Main::printNumbers1);
        Thread two = new Thread(Main::printNumbers2);

        //starting the threads
        one.start();
        two.start();
    }
}

Output

10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10

Java Most Popular & Searched Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.