Two ways to create multi-threads

Two ways to implement multithreading:

1. Inherit the Thread class

public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i%2==0){
                System.out.println("子线程-------------->"+i);
            }
        }
    }
}

First define a class to inherit the Thread class and override the run method

public class Test {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        for (int i = 0; i < 100; i++) {
            if(i%2==0){
                System.out.println("主线程---------->"+i);
            }
        }
    }
}

Create an object in the test class, call the start method, and write a program in the main thread. Let's run the program and see the results.

 The output results of the two programs are output alternately, indicating that the two programs are concurrent at a macro level.

2. Implement the Runnable interface

public class RunThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i%2!=0){
                System.out.println("子线程----------->"+ i);
            }
        }
    }
}

First write a class so that it implements the Runnable method and overrides the run method

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new RunThread());

        thread.start();

        for (int i = 0; i < 100; i++) {
            if(i%2!=0){
                System.out.println("主线程--------->"+i);
            }
        }
    }
}

Create a Thread object in the test class and call the start method. The running results are as follows:

 You can see that the program is also executed concurrently, and the effect is the same as if we inherited the Thread class.

 If you have complex thread operation requirements, then choose to inherit Thread. If you just want to simply perform a task, then implement runnable.

Guess you like

Origin blog.csdn.net/weixin_65379795/article/details/130058981