ConcurrentDictionary

例子1

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var dic = new ConcurrentDictionary<int, int>();

            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine(i + "  count");
                runInNewThread(i);
            }

            void runInNewThread(int i)
            {
                var thread = new Thread(para => dic.GetOrAdd(1, _ => getNum((int)para)));
                thread.Start(i);
            }

            int getNum(int i)
            {
                Console.WriteLine($"Factory invoke. got {i}");
                return i;
            }

            Console.ReadKey();
        }
}
  • 運(yùn)行結(jié)果可能為以下之一


    例1-1

    例1-2

    例1-3

    例1-4

    例1-5

例子2

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();

            // Bombard the ConcurrentDictionary with 10000 competing AddOrUpdates
            Parallel.For(0, 10000, i =>
            {
                // Initial call will set cd[1] = 1.  
                // Ensuing calls will set cd[1] = cd[1] + 1
                cd.AddOrUpdate(1, 1, (key, oldValue) => oldValue + 1);
            });

            Console.WriteLine("After 10000 AddOrUpdates, cd[1] = {0}, should be 10000", cd[1]);

            // Should return 100, as key 2 is not yet in the dictionary
            int value = cd.GetOrAdd(2, (key) => 100);
            Console.WriteLine("After initial GetOrAdd, cd[2] = {0} (should be 100)", value);

            // Should return 100, as key 2 is already set to that value
            value = cd.GetOrAdd(2, 10000);
            Console.WriteLine("After second GetOrAdd, cd[2] = {0} (should be 100)", value);

            Console.ReadKey();
        }
}
  • 運(yùn)行結(jié)果如下


    例2

例子3

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var task1 = Task.Run(() => PrintValue("JeffckWang"));
            var task2 = Task.Run(() => PrintValue("cnblogs"));
            Task.WaitAll(task1, task2);

            PrintValue("JeffckyWang from cnblogs");
            Console.WriteLine($"Run count: {_runCount}");

            Console.ReadKey();
        }


        private static readonly ConcurrentDictionary<string, string> _dictionary
            = new ConcurrentDictionary<string, string>();
        private static int _runCount = 0;

        public static void PrintValue(string valueToPrint)
        {
            var valueFound = _dictionary.GetOrAdd("key",
                        x =>
                        {
                            Interlocked.Increment(ref _runCount);
                            Thread.Sleep(100);
                            return valueToPrint;
                        });
            Console.WriteLine(valueFound);
        }
    }
}

  • 運(yùn)行結(jié)果可能為以下之一


    例3-1

    例3-2

例子4

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var task1 = Task.Run(() => PrintValue("JeffckWang"));
            var task2 = Task.Run(() => PrintValue("cnblogs"));
            Task.WaitAll(task1, task2);

            PrintValue("JeffckyWang from cnblogs");
            Console.WriteLine($"Run count: {_runCount}");

            Console.ReadKey();
        }

        private static int _runCount = 0;

        private static readonly ConcurrentDictionary<string, Lazy<string>> _lazyDictionary
          = new ConcurrentDictionary<string, Lazy<string>>();

        public static void PrintValue(string valueToPrint)
        {
            var valueFound = _lazyDictionary.GetOrAdd("key",
              x => new Lazy<string>(
                  () =>
                  {
                      Interlocked.Increment(ref _runCount);
                      Thread.Sleep(100);
                      return valueToPrint;
                  }));
            Console.WriteLine(valueFound.Value);
        }
    }
}

  • 運(yùn)行結(jié)果可能為以下之一


    例4-1

    例4-2

具體過程分析請(qǐng)看參考

參考
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等。 首先講...
    李欣陽閱讀 2,591評(píng)論 1 15
  • 世間 是否有一種十萬分不舍的真摯情感,而你卻必須放棄? 是否也有人因?yàn)樘^喜歡某個(gè)人或者愛某個(gè)人但必須放手狠心說再...
    井溢閱讀 311評(píng)論 0 3
  • 麥田里的土壤不能根植樹林。 草原的風(fēng)馬,也不如往前向往。 遺憾,像囚禁的飛鳥。 我如魚刺卡于咽喉, 如信仰死于昨天...
    十二月_無言閱讀 130評(píng)論 3 4
  • 明天一大早就要出發(fā)了,心情好復(fù)雜!今天安頓收拾了一天,糾結(jié)癥又犯了,到底哪些東西可以不帶?帶的太多提不動(dòng),但一些物...
    土左旗357李新燕閱讀 152評(píng)論 0 0
  • 今天是平安夜 想寫的東西太多 大概有一籮筐。考完研周圍的同學(xué)都得到解放 考好考差 回家過年。 希望大家安安靜靜 我...
    徐走你閱讀 171評(píng)論 0 0

友情鏈接更多精彩內(nèi)容