后端与系统架构544 字

Java实现多线程的方式,手写

·全库 360 / 611

《Java实现多线程的方式,手写》共 0.1 万字,通篇围绕 需求 展开,归在「后端与系统架构」这一层。

覆盖需求

适合给 AI 系统搭底座、要管得住的人

目录骨架(3 节)
  1. 1. 继承Thread类
  2. 2. 实现Runnable接口
  3. 3. 实现Callable接口并配合Future与ExecutorService使用
  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口并配合Future与ExecutorService使用

下面我将详细介绍每种方式,并提供相应的示例代码。

1. 继承Thread类

继承Thread类并重写run()方法是实现多线程的最简单方式之一。

class MyThread extends Thread {

    @Override

    public void run() {

        for (int i = 0; i < 5; i++) {

            System.out.println(Thread.currentThread().getName() + " is running: " + i);

        }

    }

    public static void main(String[] args) {

        MyThread t1 = new MyThread();

        MyThread t2 = new MyThread();

        t1.start();

        t2.start();

    }

}

2. 实现Runnable接口

实现Runnable接口并将其实例传递给Thread对象。

class MyRunnable implements Runnable {

    @Override

    public void run() {

        for (int i = 0; i < 5; i++) {

            System.out.println(Thread.currentThread().getName() + " is running: " + i);

        }

    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new MyRunnable());

        Thread t2 = new Thread(new MyRunnable());

        t1.start();

        t2.start();

    }

}

3. 实现Callable接口并配合Future与ExecutorService使用

Callable接口与Runnable接口的不同在于,Callable可以返回执行结果,并且可以抛出异常。通常与Future和ExecutorService一同使用

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

class MyCallable implements Callable<Integer> {

    @Override

    public Integer call() throws Exception {

        int sum = 0;

        for (int i = 0; i < 5; i++) {

            sum += i;

            System.out.println(Thread.currentThread().getName() + " is running: " + i);

        }

        return sum;

    }

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future<Integer> future1 = executor.submit(new MyCallable());

        Future<Integer> future2 = executor.submit(new MyCallable());

        try {

            System.out.println("Result of future1: " + future1.get());

            System.out.println("Result of future2: " + future2.get());

        } catch (InterruptedException | ExecutionException e) {

            e.printStackTrace();

        }

        executor.shutdown();

    }

}

小结

上述三种方式各有优缺点:

  1. 继承Thread类:
  • 优点: 简单,直接继承Thread类即可。
  • 缺点: Java只允许单继承,如果已经继承了其他类就无法再继承Thread。
  1. 实现Runnable接口:
  • 优点: 可以避免单继承的局限性。
  • 缺点: 无法直接获得执行结果。
  1. 实现Callable接口:
  • 优点: 可以返回结果或抛出异常。
  • 缺点: 需要配合Future和ExecutorService,相对复杂一些。

选择哪种方式取决于具体需求,如果需要返回结果或处理异常推荐使用Callable接口,如果只是简单的多线程操作Runnable接口足够。

资料里没有你的场景?

把你手上的数据和想解决的那个环节发上来,我们按具体情况回,不复述方法论。

发布需求