zoukankan      html  css  js  c++  java
  • InterLocked 的使用,关键是那一刻得到线程安全的正确值。

    // This example demonstrates a thread-safe method that adds to a
    // running total. It cannot be run directly. You can compile it
    // as a library, or add the class to a project.
    using System.Threading;

    public class ThreadSafe {
    // totalValue contains a running total that can be updated
    // by multiple threads. It must be protected from unsynchronized
    // access.
    private int totalValue = 0;

    // The Total property returns the running total.
    public int Total {
    get { return totalValue; }
    }

    // AddToTotal safely adds a value to the running total.
    public int AddToTotal(int addend) {
    int initialValue, computedValue;
    do {
    // Save the current running total in a local variable.
    initialValue = totalValue;

    // Add the new value to the running total.
    computedValue = initialValue + addend;

    // CompareExchange compares totalValue to initialValue. If
    // they are not equal, then another thread has updated the
    // running total since this loop started. CompareExchange
    // does not update totalValue. CompareExchange returns the
    // contents of totalValue, which do not equal initialValue,
    // so the loop executes again.
    } while (initialValue != Interlocked.CompareExchange(
    ref totalValue, computedValue, initialValue));
    // If no other thread updated the running total, then
    // totalValue and initialValue are equal when CompareExchange
    // compares them, and computedValue is stored in totalValue.
    // CompareExchange returns the value that was in totalValue
    // before the update, which is equal to initialValue, so the
    // loop ends.

    // The function returns computedValue, not totalValue, because
    // totalValue could be changed by another thread between
    // the time the loop ends and the function returns.
    return computedValue;
    }
    }

  • 相关阅读:
    画江恩线
    从装饰者模式的理解说JAVA的IO包
    Form表单标签的Enctype属性的作用及应用示例介绍
    spring中的通配符
    简析SynchronousQueue,LinkedBlockingQueue,ArrayBlockingQueue
    Java数据封装成树形结构,多级
    详解InitializingBean、initMethod和@PostConstruct
    SpringCloud确保服务只能通过gateway转发访问,禁止直接调用接口访问
    Spring中的InitializingBean接口的使用
    Linux下Centos7对外开放端口
  • 原文地址:https://www.cnblogs.com/jiangzhen/p/2745624.html
Copyright © 2011-2022 走看看