并发编程--01并发编程的基础

博客介绍了线程的状态,包括启动和终止方式,如start启动、stop已过时、interrupt优雅中断等,还提到通过指令方式控制线程。同时阐述了线程的安全性问题,有可见性、原子性和有序性问题,以及CPU高速缓存相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程的状态:

      1 NEW   初始状态,没有调用start方法   A thread that has not yet started is in this state.
   
     * 2 RUNNABLE  运行状态   A thread executing in the Java virtual machine is in this state.
    
     * 3 BLOCKED   阻塞  A thread that is blocked waiting for a monitor lock
     * 			等待阻塞  wait
     *         同步阻塞   synchronized
     * 			其他阻塞  sleep /  join  
    
     * 4 WAITING  等待  A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
    
     * 5 TIMED_WAITING   时间等待 A thread that is waiting for another thread to perform an action for up to a specified waiting time is in tsis state.
 
     * 6 TERMINATED  终止  A thread that has exited is in this state.

在这里插入图片描述

线程的启动和终止:
start native

stop – 过时, 相当于 kill

interrupt 优雅中断

通过指令的方式 votatile Boolean isStop = false

Thread.interrupted(); 对设置的中断标识的线程进行复位

public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            while (true){
                boolean in = Thread.currentThread().isInterrupted();
                if(in){
                    System.out.println("before:"+in);
                    Thread.interrupted();       //设置复位
                    System.out.println("after:"+Thread.currentThread().isInterrupted());
                }
            }
        });

        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();
    }

线程的安全性问题:

  1. 可见性问题

  2. 原子性问题

  3. 有序性问题: 编译器的优化 指令重排序 但原则是保证不影响最终的结果。

CPU的高速缓存
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值