【47、创建线程的几种方式】

77 阅读1分钟

在Java中,可以使用以下几种方式创建线程:

  1. 继承Thread类并重写run()方法:
javaCopy code
class MyThread extends Thread {
    public void run() {
        // 线程执行的代码
    }
}

// 创建并启动线程
MyThread myThread = new MyThread();
myThread.start();
  1. 实现Runnable接口:
javaCopy code
class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的代码
    }
}

// 创建并启动线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
  1. 实现Callable接口并使用FutureTask包装:
javaCopy code
class MyCallable implements Callable<Integer> {
    public Integer call() {
        // 线程执行的代码
        return 1;
    }
}

// 创建并启动线程
MyCallable myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();

// 获取线程执行结果
int result = futureTask.get();
  1. 使用线程池:
javaCopy code
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(() -> {
    // 线程执行的代码
});

以上都是Java中常用的创建线程的方式,每种方式都有自己的适用场景。