2 threads print odd and even numbers within 100 respectively (java)

Method 1: The way to inherit the Thread class

public class ThreadDemo {
    
    
    public static void main(String[] args) {
    
    
        MyThread1 myThread1 = new MyThread1();
        MyThread2 myThread2 = new MyThread2();
        myThread1.start();
        myThread2.start();
    }
}
class MyThread1 extends Thread{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            if(i % 2 == 0){
    
    
                System.out.println(currentThread().getName()+":"+i);
            }
        }
    }
}

class MyThread2 extends Thread{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            if(i % 2 != 0){
    
    
                System.out.println(currentThread().getName()+":"+i);
            }
        }
    }
} 

Simplify with anonymous subclasses

public class ThreadDemo {
    
    
    public static void main(String[] args) {
    
    
    
        new Thread(){
    
    
            @Override
            public void run() {
    
    
                for (int i = 0; i < 100; i++) {
    
    
                    if(i % 2 == 0){
    
    
                        System.out.println(currentThread().getName()+":"+i);
                    }
                }
            }
        }.start();

        new Thread(){
    
    
            @Override
            public void run() {
    
    
                for (int i = 0; i < 100; i++) {
    
    
                    if(i % 2 != 0){
    
    
                        System.out.println(currentThread().getName()+":"+i);
                    }
                }
            }
        }.start();
    }
}

Guess you like

Origin blog.csdn.net/qq_45689267/article/details/108372485