多线程学习笔记

1.什么是线程

进程是资源分配最小单位,线程是程序执行的最小单位。

2.什么是进程

 cup从硬盘中读取一段程序到内存中,该执行程序的实例就叫做进程

一个程序如果被cpu多次 读取到内存中,则变成多个独立的进程

 3.为什么进程中还需要线程呢?

同一个 应用程序中,更好并行处理

4.并行/串行区别

串行也就是单线程执行,代码执行效率非常低,

并行就是多个线程并行执行,效率也较高。

5.使用多线程一定会提高 效率吗?

不一定,需要啊cpu调度的算法就是先把前一个任务的cpu上下文(也是就是cpu寄存器和程序计数器)保存起来,然后加载到新任务的上下文到这些寄存器和程序计数器 ,最后再跳到程序计数器新位置 。

上下文切换就是cpu从执行该线程换到执行另外的线程

6.多线程创建方式

1)继承 Thread 类创建线程

2)实现Runnable接口创建线程

3)使用匿名内部类的形式创建线程

4)使用lambada表达式创建线程

5)使用Callable和 Futrue创建线程

6)使用线程池列如用Exrcutor框架

7)spring @Asyn异步注解

 6-1继承 Thread 类创建线程

public class test extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"这是子线程");
    }

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"这是主线程");
        new test().start();//运行线程
    }
}

6-2实现Runnable接口创建线程

public class test implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"这是子线程");
    }

    public static void main(String[] args) {
        new Thread(new test()).start();
    }
}

6-3使用匿名内部类的形式创建线程

public class test {
  

    public static void main(String[] args) {
       new Thread(new Runnable() {
           @Override
           public void run() {
               System.out.println(Thread.currentThread().getName()+"这是子线程");
           }
       }).start();
    }
}

6-4使用lambada表达式创建线程

public class test {


    public static void main(String[] args) {
        new Thread(() -> {

            System.out.println(Thread.currentThread().getName() + "这是子线程");
        
        }).start();
    }
}

6-5使用Callable和 Futrue创建线程

使用Callable和Futue线程可以获取到返回结果,底层基于LockSupport

public class test implements Callable<Integer> {


    public static void main(String[] args)throws Exception {
        test test = new test();
        final FutureTask<Integer> task = new FutureTask<>(test);
        new Thread(task).start();
        Integer integer = task.get();
        System.out.println(Thread.currentThread().getName()+","+integer);
    }

    @Override
    public Integer call()  {
        System.out.println(Thread.currentThread()+"开始执行");
        try {
            Thread.sleep(3000);

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread()+"返回1");
        return 1;
    }
}

6-6使用线程池列如用Exrcutor框架

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

public class Test {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
            System.out.println(Thread.currentThread() + "我是子线程");

        });
        executorService.shutdown();

    }
}

 6-7spring @Asyn异步注解结合线程

这个注解不能用test方法来测试,因为test方法底层是static方法,下面我是用controller来测试

一定要在在启动类添加@EnableAsync //开启异常注解

 */
@Slf4j
@RestController
public class Test02 {
    @Autowired
    private Test01 test01;

    @RequestMapping("/")
    @Test
    public void run() {
        log.info("开始");
        new Thread(new Runnable() {
            @Override
            public void run() {
                test01.print();
            }
        }).start();
        log.info("结束");
    }
}


@Slf4j
@Component
public class Test01 {
    @Async
    public void print() {
        try {
            Thread.sleep(3000);
            log.info("异常");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}

 7.手写@Asyn异步注解

import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
    String value() default "";
}

添加aop,看触发情况

package com.example.list.controller;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ExThreadAop {

    /**
     * 环绕通知
     */
    @Around(value = "@annotation(com.example.list.controller.Async)")
    public Object around(ProceedingJoinPoint joinPoint) {
        try {
            log.info("环绕通知开始执行......");
            joinPoint.proceed();
            return "环绕通知";
        } catch (Throwable throwable) {
            return "系统错误";
        }
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Royalreairman

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

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

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

打赏作者

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

抵扣说明:

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

余额充值