Q:

Java code to run multiple threads in a program

belongs to collection: Java Most Popular & Searched Programs

0

Java code to run multiple threads in a program

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java code for pause the execution... >>