多线程19-线程池批量插入线程
Posted shidengyun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程19-线程池批量插入线程相关的知识,希望对你有一定的参考价值。
class Program
{
static void UseThreads(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Scheduling work by creating threads");
for (int i = 0; i < numberOfOperations; i++)
{
var thread = new Thread(() =>
{
Console.WriteLine("current Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
thread.Start();
}
countdown.Wait();
Console.WriteLine();
}
}
static void UseThreadPool(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Starting work on a threadPool");
for (int i = 0; i < numberOfOperations; i++)
{
ThreadPool.QueueUserWorkItem(x =>
{
Console.WriteLine("current Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
}
countdown.Wait();
Console.WriteLine();
}
}
static void Main()
{
const int numberOfOpeartions = 3000;
var sw = new Stopwatch();
sw.Start();
UseThreads(numberOfOpeartions);
sw.Stop();
Console.WriteLine("Excution time using threads:{0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
UseThreadPool(numberOfOpeartions);
sw.Stop();
Console.WriteLine("Execution time using threads:{0}", sw.ElapsedMilliseconds);
}
}
{
static void UseThreads(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Scheduling work by creating threads");
for (int i = 0; i < numberOfOperations; i++)
{
var thread = new Thread(() =>
{
Console.WriteLine("current Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
thread.Start();
}
countdown.Wait();
Console.WriteLine();
}
}
static void UseThreadPool(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Starting work on a threadPool");
for (int i = 0; i < numberOfOperations; i++)
{
ThreadPool.QueueUserWorkItem(x =>
{
Console.WriteLine("current Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
}
countdown.Wait();
Console.WriteLine();
}
}
static void Main()
{
const int numberOfOpeartions = 3000;
var sw = new Stopwatch();
sw.Start();
UseThreads(numberOfOpeartions);
sw.Stop();
Console.WriteLine("Excution time using threads:{0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
UseThreadPool(numberOfOpeartions);
sw.Stop();
Console.WriteLine("Execution time using threads:{0}", sw.ElapsedMilliseconds);
}
}
以上是关于多线程19-线程池批量插入线程的主要内容,如果未能解决你的问题,请参考以下文章
springboot利用ThreadPoolTaskExecutor多线程批量插入百万级数据
大数据批量新增or修改太慢太Low,线程池CountDownLatchCompletableFuture完美解决