当前位置: 首页 > news >正文

Java底层并发:线程、volatile

在Java的并发编程中,线程、volatile关键字、原子性、临界区以及DelayQueue是一些重要概念。理解这些内容对于编写高效且线程安全的程序至关重要。

在这里插入图片描述

1. 线程的基本概念

Java中的线程是程序执行的最小单位。Java提供了多种创建线程的方式,最常用的方式是继承Thread类或实现Runnable接口。

示例代码

class MyThread extends Thread {@Overridepublic void run() {System.out.println("Thread is running");}
}public class ThreadExample {public static void main(String[] args) {MyThread thread = new MyThread();thread.start();}
}

原理分析

线程的创建和管理是由JVM和操作系统共同完成的。JVM通过线程调度算法,决定哪个线程在什么时间执行。

2. volatile关键字

volatile关键字用于修饰变量,确保对该变量的读写操作是可见的。

示例代码

class VolatileExample {private volatile boolean running = true;public void run() {while (running) {// do something}System.out.println("Stopped");}public void stop() {running = false;}public static void main(String[] args) throws InterruptedException {VolatileExample example = new VolatileExample();Thread thread = new Thread(example::run);thread.start();// 让线程运行一段时间Thread.sleep(1000);example.stop();}
}

原理分析

使用volatile保证了变量的可见性,并禁止指令重排序,提升了并发效率。

3. 原子性

原子性是指一个操作要么全部完成,要么全部不执行。Java中可以通过Atomic类实现原子操作。

示例代码

import java.util.concurrent.atomic.AtomicInteger;class AtomicExample {private AtomicInteger count = new AtomicInteger(0);public void increment() {count.incrementAndGet();}public int getCount() {return count.get();}
}public class Main {public static void main(String[] args) {AtomicExample example = new AtomicExample();example.increment();System.out.println("Count: " + example.getCount());}
}

原理分析

Atomic类使用CAS(Compare And Swap)算法实现原子性,避免了使用锁带来的性能损失。

4. 临界区

临界区是指访问共享资源的代码区域。通过synchronized关键字或显式锁来管理临界区。

示例代码

class CriticalSection {private int count = 0;public void increment() {synchronized (this) {count++;}}public int getCount() {return count;}
}

原理分析

使用synchronized可以防止多个线程同时访问临界区,从而避免数据竞争,但可能导致性能瓶颈。

5. DelayQueue

DelayQueue是一个实现了BlockingQueue接口的队列,主要用于实现延迟任务。

示例代码

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;class DelayedItem implements Delayed {private final long delayTime;private final long expirationTime;public DelayedItem(long delayTime) {this.delayTime = delayTime;this.expirationTime = System.currentTimeMillis() + delayTime;}@Overridepublic long getDelay(TimeUnit unit) {return unit.convert(expirationTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);}@Overridepublic int compareTo(Delayed o) {return Long.compare(this.expirationTime, ((DelayedItem) o).expirationTime);}
}public class DelayQueueExample {public static void main(String[] args) throws InterruptedException {DelayQueue<DelayedItem> queue = new DelayQueue<>();queue.put(new DelayedItem(5000));System.out.println("Waiting for item...");DelayedItem item = queue.take(); // 等待5秒System.out.println("Item is taken after delay");}
}

原理分析

DelayQueue使用优先级队列管理元素,当调用take()方法时,线程会被阻塞,直到队列中有可用元素。

6. 结论

理解Java中的线程、volatile、原子性、临界区和DelayQueue的概念,有助于我们编写高效且安全的多线程程序。在并发编程中,选择合适的工具和方法,是编写高质量代码的关键。


http://www.mrgr.cn/news/38094.html

相关文章:

  • 清华提出时间序列大模型:面向通用时序分析的生成式Transformer | ICML 2024
  • 转行大模型的必要性与未来前景:迎接智能时代的浪潮
  • element-plus中日历组件设置起始为周一
  • protobuff中的required有什么用?
  • 【深度学习】05-Rnn循环神经网络-01- 自然语言处理概述/词嵌入层/循环网络/文本生成案例精讲
  • MYSQL-查看表中字段属性语法(三)
  • 【Mysql】Mysql数据库基本操作-------DDL(下)
  • 【项目文档】软件系统培训方案(Doc原件2024)
  • 【保姆级教程】批量下载Pexels视频Python脚本(以HumanVid数据集为例)
  • laravel - Facades
  • 华为OD机试 - 西天取经 - 广度优先搜索BFS(Java 2024 E卷 200分)
  • 双十一儿童耳勺哪款好?双十一儿童专用掏耳神器推荐!
  • Meta AI 发布 Llama 3.2
  • C++学习:模版进阶:非类型模板参数 特化 分离编译
  • [leetcode刷题]面试经典150题之9python哈希表详解(知识点+题合集)
  • 图像超分辨率(SR)
  • winsoft公司Utils组件功能简介
  • 数据结构 ——— 顺序表oj题:编写函数,合并两个有序数组
  • excel统计分析(3): 一元线性回归分析
  • 计算物理精解【7】-计算原理精解【4】