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 »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.