串行和并行
1.先要理解并行和并发的区别:
例子:一个打卡机:一条队伍排队打卡,如果把队伍分成两条对方交替打卡。这种情况叫并发 !
一个打卡机:一条队伍排队打卡,如果把打卡机弄成两台去打卡。这种情况叫并行 !
多线程理解为队伍,cup理解为打卡机!细想 哈
2.串行和并行的区别:
串行一个个来,并行一起来 哈
例子实现: ConcurrentBag<T> 为线程安全集合 List<T> 非线程安全集合
private static void Run1()
{
Console.WriteLine("任务1:3s");
Thread.Sleep(3000);
}
private static void Run2()
{
Console.WriteLine("任务2:5s");
Thread.Sleep(5000);
}
private static void ParallerTest01()
{
var watch = Stopwatch.StartNew();
watch.Start();
Run1();
Run2();
Console.WriteLine("串行耗时:{0}", watch.ElapsedMilliseconds);
watch.Restart();
Parallel.Invoke(Run1, Run2);
Console.WriteLine("并行耗时:{0}", watch.ElapsedMilliseconds);
Console.Read();
}
private static void ParallerTest02()
{
for (var j = 1; j < 5; j++)
{
Console.WriteLine("第{0}次循环", j);
#region 并行
var bag = new ConcurrentBag<int>();
var watch = Stopwatch.StartNew();
watch.Start();
Parallel.For(0, 20_000_000, i =>
{
bag.Add(i);
});
Console.WriteLine($"并行耗时:{watch.ElapsedMilliseconds}");
#endregion
#region 串行
var bag1 = new ConcurrentBag<int>();
watch = Stopwatch.StartNew();
watch.Start();
for (var i = 0; i < 20_000_000; i++)
{
bag1.Add(i);
}
Console.WriteLine($"串行耗时:{watch.ElapsedMilliseconds}");
#endregion
}
}

浙公网安备 33010602011771号