ITPub博客

首页 > 大数据 > Hadoop > 可变资源:资源的状态(值)可以被修改(如int计数器、HashMap的元素)

可变资源:资源的状态(值)可以被修改(如int计数器、HashMap的元素)

投稿 Hadoop 作者:ecclw459 时间:2026-01-30 17:31:35 0 删除 编辑
  • 经典的i++ 操作。它在底层分为“读取-修改-写入”三个步骤。如果两个线程同时读取 i=1,各自加1后写回,结果是2而不是3。
  1. 直接原因:三大特性被破坏
  • Java内存模型(JMM)定义的多线程并发三大核心特性,任何一个被破坏都会引发线程安全问题:
    • 原子性:一个操作(如count++)包含“读 - 改 - 写”三步,非原子操作会被多线程交错执行;
    • 可见性:线程修改共享变量后,不会立即同步到主内存,其他线程读取的仍是旧值;
    • 有序性:JVM的指令重排序优化,会导致多线程下执行顺序混乱(如未加volatile的双重检查锁单例)。

线程安全问题的解决方案

  • 核心思路:要么避免共享可变资源(从根源消除问题),要么控制并发访问规则(保证三大特性)。
方案1:避免共享可变资源(优先推荐)
  • 栈封闭(局部变量):局部变量存储在线程私有栈中,每个线程有独立副本,天然线程安全。


ublic class StackClosedDemo {     // 每个线程调用该方法时,都会创建独立的count副本     public void calculate () {         int count = 0 ;        count++; // 无线程安全问题        System.out.println(Thread.currentThread().getName() + ": " + count);    }     public static void main (String[] args) {         StackClosedDemo demo = new StackClosedDemo ();         // 10个线程各自操作自己的局部变量         for ( int i = 0 ; i < 10 ; i++) {             new Thread (demo::calculate, "Thread-" + i).start();

// 自定义不可变类(final类+final成员变量+无setter) public final class ImmutableUser {     private final String name;     private final int age;     public ImmutableUser (String name, int age) {         this .name = name;         this .age = age;    }     // 仅提供getter,无setter   jrs.xxthtz.com     public String getName () { return name; }

public class ThreadLocalDemo {     // 每个线程有独立的Integer副本,初始值为0     private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0 );     public void increment () {        threadLocal.set(threadLocal.get() + 1 );        System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get());    }     public static void main (String[] args) {   jrszb.jnhjpj.cn        ThreadLocalDemo demo = new ThreadLocalDemo ();         // 3个线程各自操作自己的副本         for ( int i = 0 ; i < 3 ; i++) {             new Thread (() -> {                 for ( int j = 0 ; j < 2 ; j++) {                    demo.increment();                }            }, "Thread-" + i).start();        }    } } // 输出(顺序可能不同): // Thread-0: 1、Thread-0: 2 // Thread-1: 1、Thread-1: 2

jrs.yccgc.cn  

public class SynchronizedDemo {     private int count = 0 ;     // 同步实例方法,锁是this对象     public synchronized void increment () {        count++;    }     public static void main (String[] args) throws InterruptedException {         SynchronizedDemo demo = new SynchronizedDemo ();         // 1000个线程执行increment         for ( int i = 0 ; i < 1000 ; i++) {             new Thread (demo::increment).start();        }


import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockDemo {     private int count = 0 ;     private Lock lock = new ReentrantLock (); // 默认非公平锁     public void increment () {        lock.lock(); // 加锁         try {            count++;        } finally {            lock.unlock(); xrhl.top2001.cn       // 释放锁,避免死锁        }    }     public static void main (String[] args) throws InterruptedException {         ReentrantLockDemo demo = new ReentrantLockDemo ();         for ( int i = 0 ; i < 1000 ; i++) {             new Thread (demo::increment).start();        }        Thread.sleep( 1000 );        System.out.println( "最终count:" + demo.count); // 输出1000

  private volatile boolean stop = false ; // 保证可见性和有序性     public void runThread () {   jrslive.xxthtz.com       new Thread (() -> {             int i = 0 ;             while (!stop) { // 能立即感知stop的修改                i++;            }            System.out.println( "线程停止,i=" + i);        }).start();    }     public static void main (String[] args) throws InterruptedException {         VolatileDemo demo = new VolatileDemo (); fkos.top2001.cn          demo.runThread();        Thread.sleep( 3000 );        demo.stop = true ; // 修改后,线程立即停止    } }


public abstract class DisposableTrtObject : DisposableObject {     protected IntPtr ptr;                       // 原生对象指针     public bool IsDisposed { get ; protected set ; }     // 安全访问原生指针(自动检查释放状态)     public IntPtr TrtPtr    {         get        {            ThrowIfDisposed();             return ptr;        }    }     // 释放非托管资源     protected override void DisposeUnmanaged()    {         if (ptr != IntPtr.Zero)        {             // 调用原生释放函数            NativeDestroy(ptr);            ptr = IntPtr.Zero;        }    } } // 使用 using 语句自动释放资源 using Runtime runtime = new Runtime(); using CudaEngine engine = runtime.deserializeCudaEngineByBlob(data, size);


// 创建 Runtime 实例 Runtime runtime = new Runtime(); string filePath = "yolov8s-obb.engine" ; // 从字节数组反序列化引擎 byte [] data = File.ReadAllBytes(filePath); using CudaEngine cudaEngine =zvr.top2001.cn     runtime.deserializeCudaEngineByBlob(data, ( ulong )data.Length); // 从文件流反序列化 using var reader = new FileStreamReader();


reader.open(filePath); using CudaEngine cudaEngine = runtime.deserializeCudaEngineByFileStreamReader(reader); // 配置 DLA(深度学习加速器) runtime.setDLACore( 0 ); jtdk.top2001.cn   // 使用 DLA 核心 0 int dlaCores = runtime.getNbDLACores();

// 查询平台能力 bool hasFP16 = builder.platformHasFastFp16();   // 是否支持 FP16 bool hasINT8 = builder.platformHasFastInt8();   // 是否支持 INT8 int maxDLABatch = builder.maxDLABatchSize();   // DLA 最大批大小 // 创建网络定义(显式批处理模式) using NetworkDefinition network = builder.createNetworkV2(  xxthtz.com    TrtNetworkDefinitionCreationFlag.kEXPLICIT_BATCH); // 创建构建器配置 using BuilderConfig config = builder.createBuilderConfig(); //   wap.dlddz.com     创建优化配置文件(用于动态形状) using OptimizationProfile profile = builder.createOptimizationProfile(); // 构建序列化网络 using HostMemory serialized = builder.buildSerializedNetwork(network, config); // 保存引擎文件 using (FileStream fs  m.jnhjpj.cn  = new FileStream( "model.engine" , FileMode.Create, FileAccess.Write)) {    fs.Write(serialized.getByteData(), 0 , ( int )serialized.Size);


int numTensors = engine.getNbIOTensors(); string inputName ihd.dlddz.com    = engine.getIOTensorName( 0 );     // 输入张量名称 string outputName = engine.getIOTensorName( 1 );   // 输出张量名称 Dims inputShape = engine.getTensorShape(inputName); TrtDataType inputType =     gzuof.cn     engine.getTensorDataType(inputName); // 创建执行上下文 using ExecutionContext context = engine.createExecutionContext(); using ExecutionContext contextStatic = engine.createExecutionContext(    TrtExecutionContextAllocationStrategy.kSTATIC); //      序列化引擎 using HostMemory memory = engine.serialize(); // 查询引擎属性 int numLayers = engine.getNbLayers(); string name = engine.getName(); long deviceMemory = engine.getDeviceMemorySize();




来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048957/viewspace-3109566/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2026-01-07

  • 博文量
    108
  • 访问量
    102109