创建线程有几种不同的方式?你喜欢哪一种?为什么?

java创建线程有四种方式:
(1)继承Thread类
(2)实现Runnable接口
(3)实现Callable接口、
(4)线程池

实现Runnable接口这种方式更受欢迎,因为这不需要继承Thread类。在应用设计中已经继承了别的对象的情况下,这需要多继承(而Java不支持多继承),只能实现接口。同时,线程池也是非常高效的,很容易实现和使用。


1、继承Thread类

import org.junit.Test;

//实现多线程的第一种方式
class MyThread extends Thread {
    private String name;

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

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name + " is running......");
        }
    }

    public static void main(String[] args) {
        Thread a = new MyThread("线程A");
        Thread b = new MyThread("线程B");
        Thread c = new MyThread("线程C");
        a.start();
        b.start();
        c.start();
    }
}

输出:

线程A is running......
线程A is running......
线程A is running......
线程A is running......
线程A is running......
线程A is running......
线程A is running......
线程A is running......
线程A is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程C is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程B is running......
线程A is running......

本质上,Thread也实现了Runnable接口

class Thread implements Runnable {
	...
}

2、实现Runnable接口

import org.junit.Test;

//实现多线程的第二种方式
class MyRunnable implements Runnable {
    private String name;

    public MyRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + " is running......");
        }
    }

    public static void main(String[] args) {
        Thread one = new Thread(new MyRunnable("线程1"));
        Thread two = new Thread(new MyRunnable("线程2"));
        Thread three = new Thread(new MyRunnable("线程3"));
        one.start();
        two.start();
        three.start();
    }
}

输出:

线程3 is running......
线程3 is running......
线程3 is running......
线程3 is running......
线程3 is running......
线程2 is running......
线程1 is running......
线程2 is running......
线程2 is running......
线程2 is running......
线程2 is running......
线程1 is running......
线程1 is running......
线程1 is running......
线程1 is running......

3、实现Callable接口

import org.junit.Test;

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

//实现多线程的第三种方式
class MyCallable implements Callable<Integer> {

    private String name;
    private Integer number;

    public MyCallable(String name, Integer number) {
        this.name = name;
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < number; i++) {
            System.out.println(name + " is running......");
        }
        return number;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //将Callable传入FutureTask
        FutureTask<Integer> ft1 = new FutureTask<Integer>(new MyCallable("线程一", 3));
        FutureTask<Integer> ft2 = new FutureTask<Integer>(new MyCallable("线程二", 4));
        FutureTask<Integer> ft3 = new FutureTask<Integer>(new MyCallable("线程三", 5));
        //将FutureTask传入Thread
        Thread t1 = new Thread(ft1);
        Thread t2 = new Thread(ft2);
        Thread t3 = new Thread(ft3);
        t1.start();
        t2.start();
        t3.start();
        //获取线程返回结果
        Integer number1 = ft1.get();
        Integer number2 = ft2.get();
        Integer number3 = ft3.get();
        System.out.println("线程一返回结果:" + number1);
        System.out.println("线程二返回结果:" + number2);
        System.out.println("线程三返回结果:" + number3);
    }
}

输出:

线程一 is running......
线程一 is running......
线程一 is running......
线程二 is running......
线程三 is running......
线程三 is running......
线程三 is running......
线程三 is running......
线程三 is running......
线程二 is running......
线程二 is running......
线程二 is running......
线程一返回结果:3
线程二返回结果:4
线程三返回结果:5

4、线程池

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

public class ThreadPool {
    public static void main(String[] args){

        //使用Executors工具类中的方法创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);

        ThreadPoolDemo demo = new ThreadPoolDemo();

        //为线程池中的线程分配任务,使用submit方法,传入的参数可以是Runnable的实现类,也可以是Callable的实现类
        for(int i=1;i<=5;i++){
            pool.submit(demo);
        }

        //关闭线程池
        //shutdown : 以一种平和的方式关闭线程池,在关闭线程池之前,会等待线程池中的所有的任务都结束,不在接受新任务
        //shutdownNow : 立即关闭线程池
        pool.shutdown();


    }
}
class ThreadPoolDemo implements Runnable{

    /**多线程的共享数据*/
    private int i = 0;

    @Override
    public void run() {
        while(i<=50){
            System.out.println(Thread.currentThread().getName()+"---"+ i++);
        }
    }
}

输出:

pool-1-thread-1---0
pool-1-thread-5---4
pool-1-thread-5---6
pool-1-thread-1---5
pool-1-thread-4---3
pool-1-thread-4---9
pool-1-thread-4---10
pool-1-thread-3---1
pool-1-thread-3---12
pool-1-thread-2---2
pool-1-thread-3---13
pool-1-thread-3---15
pool-1-thread-3---16
pool-1-thread-3---17
pool-1-thread-3---18
pool-1-thread-3---19
pool-1-thread-3---20
pool-1-thread-3---21
pool-1-thread-3---22
pool-1-thread-4---11
pool-1-thread-4---24
pool-1-thread-4---25
pool-1-thread-4---26
pool-1-thread-4---27
pool-1-thread-4---28
pool-1-thread-4---29
pool-1-thread-4---30
pool-1-thread-4---31
pool-1-thread-4---32
pool-1-thread-4---33
pool-1-thread-4---34
pool-1-thread-4---35
pool-1-thread-4---36
pool-1-thread-4---37
pool-1-thread-4---38
pool-1-thread-1---8
pool-1-thread-1---40
pool-1-thread-5---7
pool-1-thread-5---42
pool-1-thread-5---43
pool-1-thread-5---44
pool-1-thread-5---45
pool-1-thread-5---46
pool-1-thread-5---47
pool-1-thread-5---48
pool-1-thread-5---49
pool-1-thread-5---50
pool-1-thread-1---41
pool-1-thread-4---39
pool-1-thread-3---23
pool-1-thread-2---14
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在 Python 中创建线程有以下几种方式: 1. 使用 `threading` 模块: 使用这种方式需要创建一个 `Thread` 类的实例, 然后调用它的 `start()` 方法来启动新线程。 2. 使用 `_thread` 模块: 这种方式与使用 `threading` 模块类似, 也需要调用 `start_new_thread()` 函数来启动新线程。 3. 使用多进程: Python 中的 `multiprocessing` 模块可以轻松地创建新的进程。 4. 使用其他第三方库: 例如 `gevent` 和 `concurrent.futures` 等库也可以用来创建线程。 ### 回答2: 在Java中,创建线程有以下几种方式: 1. 继承Thread类:继承Thread类并重写其run方法,然后实例化该类的对象,调用start方法启动线程。示例代码如下: ``` public class MyThread extends Thread { @Override public void run() { // 线程要执行的代码 } } // 创建并启动线程 MyThread thread = new MyThread(); thread.start(); ``` 2. 实现Runnable接口:实现Runnable接口,并实现其run方法,然后创建Thread对象并将Runnable实例作为参数传递给Thread对象,最后调用start方法启动线程。示例代码如下: ``` public class MyRunnable implements Runnable { @Override public void run() { // 线程要执行的代码 } } // 创建并启动线程 MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); ``` 3. 使用Callable和Future:使用Callable接口代替Runnable接口,重写call方法,然后创建ExecutorService对象,通过submit方法提交Callable对象,最后得到Future对象并通过get方法获取结果。示例代码如下: ``` public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { // 线程要执行的代码 return result; } } // 创建线程池并提交Callable对象 ExecutorService executor = Executors.newFixedThreadPool(1); MyCallable callable = new MyCallable(); Future<Integer> future = executor.submit(callable); // 获取线程结果 Integer result = future.get(); // 关闭线程池 executor.shutdown(); ``` 通过以上几种方式,可以灵活地创建和启动线程,并执行相应的任务。 ### 回答3: 创建线程方式有以下几种: 1. 使用继承Thread类:创建一个新的类,继承自Thread类,并重写run()方法,在run()方法中定义线程要执行的任务。然后实例化这个新类的对象,并调用对象的start()方法来启动线程。 2. 实现Runnable接口:创建一个新的类,实现Runnable接口,并实现其中的run()方法。然后实例化这个新类的对象,并将对象作为参数传递给Thread类的构造方法创建Thread对象。最后调用Thread对象的start()方法启动线程。 3. 使用Callable和Future接口:创建一个新的类,实现Callable接口,并实现其中的call()方法。然后利用ExecutorService线程池的submit()方法提交Callable对象,得到一个Future对象,通过Future对象的get()方法获取线程的返回值。 4. 使用线程池:通过ExecutorService线程池来管理线程创建和执行。可以使用ThreadPoolExecutor类来自定义线程池的大小和其他相关参数。 这些方式可以根据实际需求选择不同的方法来创建线程。使用继承Thread类或实现Runnable接口比较简单,适合简单的线程任务。使用Callable和Future接口可以获取线程的返回值。使用线程池可以有效管理线程创建和执行,提高系统资源的利用率。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值