Everyone says that Java has three ways to create threads! Shocking scam in concurrent programming!

In Java, creating threads is a very non-trivial task. A thread is a lightweight sub-process that can be executed in parallel to improve the execution efficiency of the program. Java provides a variety of ways to create threads, but many people think that Java has three ways to create threads, which are继承Thread类、实现Runnable接口和使用线程池。

But, you know what? In fact, in the process of creating a thread, there are many ways to choose besides the methods described above. Today, let's uncover this shocking secret, and let's take a look at the eight-legged essay on thread creation in Java concurrent programming.

1. The method of creating a thread:

1. Inherit the Thread class to create threads

This is the most basic way to create a thread. We can create a custom thread class by inheriting the Thread class , and then rewrite the run() method to implement the thread logic.

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        // 线程逻辑
    }
}

// 创建并启动线程
MyThread myThread = new MyThread();
myThread.start();

2. Implement the Runnable interface to create threads

This is another common way to create threads. We can create a custom thread class by implementing the Runnable interface, then instantiate the class and pass it to the constructor of the Thread class, and finally call the start() method to start thread.

public class MyRunnable implements Runnable {
    
    

@Override

public void run() {
    
    

// 线程逻辑

}

}

// 创建并启动线程

MyRunnable myRunnable = new MyRunnable();

Thread thread = new Thread(myRunnable);

thread.start();

3. Implement the Callable interface to create threads

The Callable interface is similar to the Runnable interface, but it can return a result and throw exceptions. We can create a custom thread class by implementing the Callable interface, then instantiate the class and pass it to the constructor of the FutureTask class, and finally call the start() method to start the thread.

public class MyCallable implements Callable {
    
    

@Override

public String call() throws Exception {
    
    

// 线程逻辑

return "result";

}

}

// 创建并启动线程

MyCallable myCallable = new MyCallable();

FutureTask futureTask = new FutureTask<>(myCallable);

Thread thread = new Thread(futureTask);

thread.start();

// 获取线程返回结果

String result = futureTask.get();

4. Use the thread pool to create threads

A thread pool is a mechanism for reusing threads to reduce the overhead of thread creation and destruction. We can create different types of thread pools through the static methods provided by the Executors class, and then submit tasks to the thread pool for execution.

ExecutorService executorService = Executors.newFixedThreadPool(10);

// 提交任务并执行

executorService.submit(new Runnable() {
    
    

@Override

public void run() {
    
    

// 线程逻辑

}

});

// 关闭线程池

executorService.shutdown();

5. Create threads using timers

Timers can be used to execute certain tasks regularly. We can create a timer through the Timer class, and then add tasks to the timer for execution.
Please add a picture description

6. Use ScheduledExecutorService to create threads

ScheduledExecutorServiceIt is a thread pool that can schedule task execution. We can use it to create a timed task or a periodic task.

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);

// 创建定时任务并执行
scheduledExecutorService.schedule(new Runnable() {
    
    
    @Override
    public void run() {
    
    
        // 线程逻辑
    }
}, 1, TimeUnit.SECONDS);

// 创建周期性任务并执行
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    
    
    @Override
    public void run() {
    
    
        // 线程逻辑
    }
}, 1, 1, TimeUnit.SECONDS);

// 关闭线程池
scheduledExecutorService.shutdown();

7. Create threads using the Fork/Join framework

The Fork/Join framework is a mechanism for executing tasks in parallel introduced in Java 7. It can split a large task into multiple small tasks to execute in parallel, and finally combine the results.

public class MyTask extends RecursiveTask {
    
    
    private int start;
    private int end;

    public MyTask(int start, int end) {
    
    
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
    
    
        if (end - start <= 1000) {
    
    
            // 执行小任务
            return 0;
        } else {
    
    
            // 拆分大任务
            int mid = (start + end) / 2;
            MyTask leftTask = new MyTask(start, mid);
            MyTask rightTask = new MyTask(mid + 1, end);
            leftTask.fork();
            rightTask.fork();

            // 合并结果
            return leftTask.join() + rightTask.join();
        }
    }
}

// 创建并执行任务
ForkJoinPool forkJoinPool = new ForkJoinPool();
MyTask myTask = new MyTask(1, 10000);
int result = forkJoinPool.invoke(myTask);

8. Create threads using Semaphore

Semaphore is a counter used to control the number of threads accessing a resource at the same time. We can create a limited thread pool through Semaphore.

Semaphore semaphore = new Semaphore(10);

// 创建并执行任务
Runnable runnable = new Runnable() {
    
    
    @Override
    public void run() {
    
    
        try {
    
    
            semaphore.acquire();
            // 线程逻辑
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            semaphore.release();
        }
    }
};

for (int i = 0; i < 100; i++) {
    
    
    new Thread(runnable).start();
}

2. The relationship between thread and thread body

When it comes to threads, everyone knows that it is an important multitasking mechanism. It allows us to perform multiple tasks at the same time, and can improve the efficiency of the program. The above also brings you many ways to create threads, but when it comes to this, I often find friends asking: What is the relationship between thread bodies and threads? In fact, to put it simply: the thread body is the specific execution code of the thread. So let's take a closer look at the relationship between threads and thread bodies!

1. The relationship between thread and thread body

In Java, thread and thread body are two different concepts.

A thread is an execution path, and the thread body is the specific execution code of the thread. Each thread has a thread body associated with it. The thread body is an instance of a class that implements the Runnable interface. The thread body can be an independent class or an inner class. After the thread is created, its run() method will be called, and the code in the run() method is the execution code of the thread body.

2. Case Description

Some friends may think that the above explanation is too written, so if the relationship between the thread body and the thread is explained through life examples, we can understand the thread as a person, and the thread body is what this person does.

For example, on the way to work, we can perform multiple tasks at the same time, such as listening to music, reading, sending text messages and so on. These tasks can be regarded as the thread body of this person. Threads are the mechanism by which this person performs multiple tasks at the same time. If there is only one of us, that person must finish one task before starting the next. This will waste a lot of time. But if there are two of us, then one can read a book and the other can listen to music, which allows multitasking and increases efficiency.

3. Code example

Let me bring you a simple code case of creating multiple threads to execute multiple tasks at the same time. The example is as follows:

public class MyThread implements Runnable {
    
    
    private String taskName;

    public MyThread(String taskName) {
    
    
        this.taskName = taskName;
    }

    @Override
    public void run() {
    
    
        for (int i = 0; i < 5; i++) {
    
    
            System.out.println(taskName + "执行了第" + (i + 1) + "次任务");
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
    
    
        MyThread thread1 = new MyThread("线程1");
        MyThread thread2 = new MyThread("线程2");
        Thread t1 = new Thread(thread1);
        Thread t2 = new Thread(thread2);
        t1.start();
        t2.start();
    }
}

In this case, we created two threads to perform different tasks. The thread body of each thread is the run() method of the MyThread class. In the run() method, each thread executes tasks 5 times, pausing for 1 second between each task. By creating multiple threads, we can perform multiple tasks at the same time and improve the efficiency of the program.

4. Summary

Through the relationship between Java threads and thread bodies introduced above, everyone should be clear. A thread is a multitasking mechanism, and the thread body is the specific execution code of the thread. In Java, we can create multiple threads to execute multiple tasks at the same time to improve the efficiency of the program. I hope the above can help you better understand the concepts of threads and thread bodies in Java.

3. Summary

Now everyone knows that creating threads is a very important operation in Java concurrent programming.

This article introduces eight different ways to create threads, including inheriting Thread class, implementing Runnable interface, implementing Callable interface, using thread pool, using timer, using ScheduledExecutorService, using Fork/Join framework and using Semaphore.

Each method has its own advantages and disadvantages, we need to choose the appropriate method to create threads according to the actual situation. At the same time, we also need to pay attention to issues such as thread safety and performance to ensure the correctness and efficiency of the program.

In life, we can also find many examples related to multi-threaded programming. For example, when cooking in the kitchen, we can assign different tasks to different people to complete, such as one person is responsible for washing vegetables, one person is responsible for cutting vegetables, one person is responsible for cooking vegetables, and so on. This increases efficiency and also avoids confusion and errors. Similarly, in the program, we can also assign different tasks to different threads to complete, so as to improve the response speed and throughput of the program. Therefore, multi-threaded programming is very important and worthy of our in-depth study and mastery. I hope it can be helpful to everyone.


Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/131132708