Multithreading implementation process in java

There are many ways to implement multithreading in Java

1. Inherit the Thread class:

class MyThread extends Thread {
    
    
    public void run() {
    
    
        // 线程执行的代码逻辑
    }
}

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

2. Implement the Runnable interface:

class MyRunnable implements Runnable {
    
    
    public void run() {
    
    
        // 线程执行的代码逻辑
    }
}

// 创建线程对象并启动线程
Thread thread = new Thread(new MyRunnable());
thread.start();

3. Use Callable and FutureTask (to obtain thread execution results):

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyCallable implements Callable<Integer> {
    
    
    public Integer call() throws Exception {
    
    
        // 线程执行的代码逻辑
        return 42;
    }
}

// 创建 Callable 对象和 FutureTask 对象
MyCallable callable = new MyCallable();
FutureTask<Integer> task = new FutureTask<>(callable);

// 创建线程对象并启动线程
Thread thread = new Thread(task);
thread.start();

// 获取线程执行结果
int result = task.get();

4. Use Executor framework and thread pool:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MyRunnable implements Runnable {
    
    
    public void run() {
    
    
        // 线程执行的代码逻辑
    }
}

// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(5);

// 提交任务给线程池执行
executor.submit(new MyRunnable());

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

These are common multi-threading implementation methods. You can choose the appropriate method to create and manage threads according to specific needs. Note that in actual development, thread safety, synchronization issues and communication between threads need to be considered.

Please note that the above sample code is for reference only and needs to be appropriately adjusted and expanded according to specific circumstances when used in practice.

Guess you like

Origin blog.csdn.net/weixin_41902931/article/details/130743173