Java 多线程

线程创建的三种方式

  1. 继承 Thread 类
  2. 实现 Runnable 接口
  3. 实现 Callable 接口
继承Thread 类
  • 子类继承 Thread 类具备多线程能力
  • 启动线程:子类对象.start()
  • 不建议使用:避免OOP单继承局限性
实现 Runnable 接口
  • 实现 Runnable 接口具有多线程能力
  • new Thread(目标对象).start()
  • 推荐使用:避免单继承局限性,方便同一个对象被多个线程使用
实现 Callable 接口
  • 实现 Callable 接口,需要返回值类型
  • 重写 call(),需要抛出异常
  • FutureTask<~> futureTask = new FutureTask<~>(new 接口的实现类());
  • new Thread(futureTask).start();
  • 获取结果:Integer integer = futureTask.get();
package com.zhang;

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

//回顾总结线程的创建
public class ThreadNew {

    public static void main(String[] args) {
        new MyThread1().start();

        new Thread(new MyThread2()).start();

        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
        new Thread(futureTask).start();

        try {
            Integer integer = futureTask.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

//1.继承 Thread 类
class MyThread1 extends Thread {
    @Override
    public void run() {
        System.out.println("This is MyThread1...");
    }
}

//2.实现 Runnable 接口
class MyThread2 implements Runnable {
    @Override
    public void run() {
        System.out.println("This is MyThread2...");
    }
}

//3.实现 Callable 接口
class MyThread3 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("This is MyThread3...");
        return 100;
    }
}

线程池的实现

package com.zhang.syn;

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

//测试线程池
public class TestPool {

    public static void main(String[] args) {
        //1.创建服务,创建线程池
        //newFixedThreadPool 参数:线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);

        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        //2.关闭连接
        service.shutdown();
    }
}


class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

笔记来源:https://www.bilibili.com/video/BV1V4411p7EF

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值