JAVA 多线程实现方法

1、继承Thread类:创建一个继承Thread类的子类,重写run方法,然后创建子类的实例。

public class MyThread extends Thread {
    public void run() {
        // 线程执行的代码
    }
}
 
// 使用
MyThread myThread = new MyThread();
myThread.start();

2、实现Runnable接口:创建一个实现了Runnable接口的类,实现run方法,然后将该类的实例传递给Thread构造器。

public class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的代码
    }
}
 
// 使用
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();

3、使用Executor框架:通过Executor框架提供的工具类创建线程池。

ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建包含10个线程的线程池
executorService.execute(new RunnableTask()); // 执行任务
executorService.shutdown(); // 关闭线程池

4、使用CallableFuture接口(与Runnable类似,但可以有返回值,并且可以处理异常)。

public class MyCallable implements Callable<Integer> {
    public Integer call() throws Exception {
        // 线程执行的代码
        return 0; // 返回值
    }
}
 
// 使用
FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
 
// 获取返回值
try {
    Integer result = futureTask.get();
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

5、使用ForkJoinPool(适用于可以并行的任务)。

ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.execute(new MyRecursiveTask()); // 执行可分割的任务
forkJoinPool.shutdown();

6、使用Future接口和CompletionService(适合当你有很多异步任务需要执行时)。

ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
 
for (int i = 0; i < 10; i++) {
    completionService.submit(new MyCallableTask());
}
 
// 获取返回结果
for (int i = 0; i < 10; i++) {
    try {
        Integer result = completionService.take().get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}
 
executorService.shutdown();

多线程+锁例子

package tech.kunyuan.authorization.controller;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Description:
 * Author: ky
 * DateTime: 2024-05-21 16:14
 */
@Slf4j
@RunWith(SpringRunner.class)
class TestControllerTest2 {
    private Integer count = 0;
    private ReentrantLock lock = new ReentrantLock();

    private void add() {
        add0();
    }

    // 不加锁,最终结果会不对
    private void add0() {
        count++;
    }

    private synchronized void add1() {
        count++;
    }

    private void add2() {
        synchronized (this) {
            count++;
        }
    }

    private void add3() {
        lock.lock();
        try {
            count++;
        }catch (Exception e) {
            log.info("{}", e);
        }finally {
            lock.unlock();
        }
    }

    private Integer getCount() {
        return count;
    }

    @Test
    void test() throws InterruptedException {
        Long timeStart = System.currentTimeMillis();
        int totalCnt = 1000;

        Thread t1 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t2 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t3 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t4 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t5 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t6 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t7 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t8 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t9 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        Thread t10 = new Thread(() -> {
            for(int i = 0; i < totalCnt; i++){
                add();
            }
        });

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();

        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
        t6.join();
        t7.join();
        t8.join();
        t9.join();
        t10.join();

        log.info("result is >>> {}", getCount());
        Long timeEnd = System.currentTimeMillis();
        log.info("spend time >>> {} ", timeEnd - timeStart);
    }

}
This entry was posted in 应用. Bookmark the permalink.