Java-多线程

概念

进程:程序的基本执行实体
线程:操作系统能够进行运算调度的最小单位,被包含在进程之中,是进程的实际运作单位
并发:同一时刻,多个指令在单个CPU上交替执行。
并行:同一时刻,多个指令在多个CPU上同时执行。

多线程第一种实现方式——重写run方法

test代码:

public class test {
    public static void main(String[] args) {
        /*
        *  多线程的第一种启动方式:
        *       1.自己重新定义一个类继承Thread
        *       2.重写run方法
        *       3.创建子类对象并启动线程
        * */

        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}

线程类代码:MyThread

public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(getName() + "hello");
        }
    }
}

多线程第二种实现方式——实现runable接口

test代码

public class test2 {
    public static void main(String[] args) {
        /*
        * 多线程第二种启动方式:
        *   1.自己定义一个类实现Runable接口
        *   2.重写里面的run方法
        *   3.创建自己的类方法
        *   4.创建一个Thread类的对象,开启线程
        * */

        // 创建MyRun对象
        MyRun mr = new MyRun();

        // 创建线程对象
        Thread t1 = new Thread(mr);
        Thread t2 = new Thread(mr);

        t1.setName("线程1");
        t2.setName("线程2");

        // 开启线程
        t1.start();
        t2.start();
    }
}

runable接口代码

package test614;

public class MyRun implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + "hello");
        }
    }
}

多线程第二种实现方式——实现Callable接口和Future接口方式实现

test代码

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

public class test3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*
        * 第3种实现方式:
        *   特点:可以获取到多线程的运行结果
        *   1.创建一个类MyCallable实现Callable接口
        *   2.重写call(有返回值,表示多线程的运行结果)
        *   3.创建MyCallable对象,表示多线程要执行的任务
        *   4.创建Future的对象(作用管理多线程运行的结果)
        *   5.创建Thread的对象并启动(表示线程)
        * */

        MyCallable mc = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<Integer>(mc);
        new Thread(ft).start();

        Integer result = ft.get();
        System.out.println(result);
    }
}

MyCallable代码

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum;
    }
}

三种实现方式的对比

实现方式的对比

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值