How Java creates threads

1. How to create a thread

  • Inherit Thread and override the run method
  • Implement the Runnable interface and override the run method
  • Implement the Callable interface and rewrite the call method (the execution result can be obtained after the task is executed)

2. Specific implementation and use

2.1. Inherit Thread and rewrite the run method

public class MyThread extends Thread {

    @Override
    public void run() {
        for (int x = 0; x < 200; x++) {
            System.out.println(x);
        }
    }

}

public class MyThreadDemo {
    public static void main(String[] args) {
        // 创建两个线程对象
        MyThread my1 = new MyThread();
        MyThread my2 = new MyThread();

        my1.start();
        my2.start();
    }
}

2.2. Implement the Runnable interface and rewrite the run method

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int x = 0; x < 100; x++) {
            System.out.println(x);
        }
    }

}

public class MyRunnableDemo {
    public static void main(String[] args) {
        // 创建MyRunnable类的对象
        MyRunnable my = new MyRunnable();

        Thread t1 = new Thread(my);
        Thread t2 = new Thread(my);

        t1.start();
        t2.start();
    }
}

3. Some problems

3.1. Difference between run() and start() methods

  • run(): It just encapsulates the code executed by the thread, and the direct call is a common method, which will only execute the tasks in the same thread without starting a new thread.
  • start(): The thread is first started, and then the JVM calls the run() method of the thread.

3.2. Which method should we use to create threads

In general, threads are created by implementing the Runnable interface for the following reasons:

  • The limitation of single inheritance in java can be avoided
  • Parallel running tasks and running mechanisms should be decoupled. If you create by inheriting the Thread class and call the start() method to start the thread, then when there are many tasks, it is too expensive to create a separate thread for each task. This problem can be solved with thread pools.

When you need to get the execution result after executing the task, you can create a thread by implementing the Callable interface.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324726874&siteId=291194637