java练习---多线程

2022/3/21 17:57:37

本文主要是介绍java练习---多线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

创建两个分线程,让其中一个线程输出1-100之间的偶数,另一个线程输出1-100之间的奇数。

MyThread1.java

package com.company;

public class MyThread1 implements Runnable{

    public MyThread1(){
        super();
    }
    
    public void run() {
        for (int i = 1; i <= 100; i++) {
               if (i % 2 == 0){
                   System.out.println("进入MyThread1运行状态——————————" + i);
               }
           }
        }
}

MyThread2.java

package com.company;

public class MyThread2 implements Runnable{

    public MyThread2(){
        super();
    }

    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0){
                System.out.println("进入MyThread2运行状态——————————" + i);
            }
        }
    }
}

Main.java

package com.company;

public class Main {

    /**
     * @param args
     * @lzx
     */

    public static void main(String[] args) {

        MyThread1 myThread1 = new MyThread1();
        MyThread2 myThread2 = new MyThread2();

        Thread thread1 = new Thread(myThread1);
        Thread thread2 = new Thread(myThread2);
        thread1.start();
        thread2.start();
    }
}





这篇关于java练习---多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程