一起学JAVA之【基础篇】多线程实现的4种方式

一起学JAVA之【基础篇】多线程实现

基本概念

并发:同一时间间隔执行两个或两个以上的任务

并行:同一时刻执行两个或两个以上的任务

同一时间间隔理解为同一时间段内(两个任务再不同时间执行,由于间隔时间很短,导致宏观上是同时) 同一时刻理解为同时

进程:资源分配的最小单位,可以由一个或者多个线程组成

线程:cpu调度的最小单位

线程状态

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GOhzYuXs-1635317661786)(D:\code\java\文档\markdown\图片\20190208203341726.png)]

Java线程实现的4种方式
###### 1、继承Thread类型,重载run 方法
class MyThread extends Thread{
    
    public void run(){
        //执行自己的业务
        System.out.println("this is my thread")
    }
    
}

class ThreadTest{
    public static void main(String[] args){
        MyThread mythread = new MyThread();
        mythread.start();//启动线程
    }
}

缺点:Java是单继承,当MyThread类需要继承其他类时就不能通过这种方式创建线程了

2、实现Runnable接口
class MyThread implements Runnable{
    public void run(){
        System.out.println("this is my runnable thread");
    }
}

class ThreadTest{
    public static void main(String[] args){
        Thread thread = new Thread(new MyThread());
        thread.start();//启动线程
        
        Thread thread1 = new Thread(() -> System.out.println("this is my runnable thread"));//lambda表达式实现
        thread1.start();
        
    }
}

底层都是调的Thread中init() 方法,只是这种传了一个Runnable 的 target

3、实现Callable配合FutureTask
class ThreadTest{
    public static void main(String[] args){
		Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return "this is call";
            }
        };
        //future 请求返回阻塞
        FutureTask<String> oneTask = new FutureTask<String>(callable);
        Thread callableThread = new Thread(oneTask);
        callableThread.start();
        String callRes = oneTask.get();
        System.out.println(callRes);
    }
}

优点:可以知道线程执行结束状态,但是是阻塞的,线程结束前都不会进行下一步操作

4、线程池(推荐使用)
class MyThread implements Runnable{
    public void run(){
        System.out.println("this is my runnable thread");
    }
}

class ThreadTest{
     	//thread pool
        ExecutorService pool = Executors.newFixedThreadPool(10);//10 是线程数量
        pool.execute(new MyThread());
}

rService pool = Executors.newFixedThreadPool(10);//10 是线程数量
pool.execute(new MyThread());
}


优点:配置一个线程池,每次需要用到的时候都从线程池中去拿,减少资源消耗
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值