简体   繁体   中英

Multi-threading to print even and odd numbers in java?

I'm a little confused about the difference between threading and multi-threading in Java as far as syntax. I need to write a program to print even numbers 0 to 30 and then odds using threading and another program to do the same thing using multi-threading. I wrote a program that runs and does what it's supposed to but I don't know whether it's threading or multi-threading, or how to go about doing the one it isn't. Here is my program-

public class OddEven extends Thread {
public static void main(String args[]){
    Runnable r1 = new Runnable1();
    Thread t1 = new Thread(r1);
    Runnable r2 = new Runnable2();
    Thread t2 = new Thread(r2);
    t1.start();
    t2.start();
  }
}
class Runnable1 implements Runnable{
public void run(){
    for(int i=0; i<=30; i+=2) {
        System.out.println(i);
    }
  }
}
class Runnable2 implements Runnable{
public void run(){
    for(int i=1; i<=30; i+=2){
        System.out.println(i);
    }
  }
}

Would this program be considered just a single thread?

public class OddEven {
public static void main(String args[]){
    for(int i=0; i<=30; i+=2) {
        System.out.println(i);
    }
    for(int i=1; i<=30; i+=2){
        System.out.println(i);
    }
}

}

Multithreading enables you to do multiple works simultaneously.

For example, if you make a game in which a boy moves forward & goes on firing as well. If you use single threading system, then either a boy could move forward or can fire on his enemy at a time. He cant do the both the works simultaneously.

In your case, when you call t1.start(); , then a new thread gets started which will execute your Runnable1's method. Then you called t2.start(); , immediately, it will also another thread gets started & your Runnable2's method will gets executed.

Both the method will get executed simultaneously. If you don't use multi threading, then only after finishing the first loop, the next loop will get start.

Multi-threading mainly use in the programs where main thread may process for a long time & you want to use other functions of the program.

Hope this helps!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM