【Java】多线程实现方式

多线程就是能充分利用CPU的等待时间,同时进行多个操作,提高效率

并发:在同一时刻,有多个指令在单个CPU上交替执行

并行:在同一时刻,有多个指令在多个CPU上同时执行

继承Thread类

优点:比较简单,可以直接使用Thread类中的方法

缺点:扩展性比较差,不能再继承其他类

thread t1 = new thread();
        thread t2 = new thread();
        t1.setName("11111");
        t2.setName("22");

        t1.start();
        t2.start();

实现Runnable接口

优点:扩展性强,还可以同时继承其他类

缺点:书写较为复杂,不能直接使用Thread类中的方法

步骤

  1. 自定义一个类实现Runable接口

  1. 重写run方法

  1. 创建此类的对象

  1. 创建一个Thread类的对象,并开启线程

public class Test {
    public static void main(String[] args) {
        thread t = new thread();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}
public class thread implements Runnable{
    public void run() {
        for (int i = 0; i < 100; i++) {
            Thread t = Thread.currentThread();
            System.out.println(t.getName() +  "hello!");
        }
    }
}

实现Callable接口

优点:扩展性强,还可以同时继承其他类

缺点:书写较为复杂,不能直接使用Thread类中的方法

特点:可以获取到多线程运行的结果

步骤:

  1. 创建一个类实现Callable接口

  1. 重写call(有返回值,为多线程运行的结果)

  1. 创建此类的对象(表示多线程要执行的任务)

  1. 创建FutureTask的对象(管理多线程运行的结果)

  1. 创建Thread类的对象,并启动(表示线程)

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        thread t = new thread();
        FutureTask<Integer> f = new FutureTask<>(t);
        Thread t1 = new Thread(f);
        t1.start();
        Integer i = f.get();
        System.out.println(i);
    }
}
public class thread implements Callable {

    @Override
    public Integer call() throws Exception {
        int s = 0;
        for (int i = 0; i <= 100 ; i++) {
            s += i;
        }
        return s;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊呜冷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值