多线程在Java中打印偶数和奇数? [英] Multi-threading to print even and odd numbers in java?

查看:315
本文介绍了多线程在Java中打印偶数和奇数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就语法而言,我对Java中的线程和多线程之间的区别感到有些困惑.我需要编写一个程序来打印偶数0到30,然后使用线程打印几率,而另一个程序使用多线程打印同样的事情.我编写了一个程序,该程序可以运行并且可以实现预期的功能,但是我不知道它是线程化还是多线程化,或者不知道如何去做.这是我的程序-

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.

在您的情况下,当您调用t1.start();时,将启动一个新线程,该线程将执行您的Runnable1's方法.然后您调用了t2.start();,立即,它将又启动另一个线程&您的Runnable2's方法将被执行.

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!!!!

这篇关于多线程在Java中打印偶数和奇数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆