一个关于多线程和for循环的问题
不知道是不是我多线程的问题,今天测试了一下,发现多线程可以并行处理完数据,可是消耗的时间却比for还长!
FOR循环代码如下:
for (int i = 0; i < 7; i++)
{
Doit(mm);
}
public static void Doit(object Dom)
{
Console.WriteLine("A"+DateTime.Now);
string ml = "";
for (int i = 0; i < 10000; i++)
{
ml += DateTime.Now.ToString();
//Console.WriteLine(DateTime.Now);
}
Console.WriteLine(DateTime.Now);
}
Thread[] ths = new Thread[12];//创建线程集合体
ParameterizedThreadStart[] pst = new ParameterizedThreadStart[12];//创建带参数的线程委托
for (int m = 0; m < 7; m++)
{
int f = m + 10;
pst[m] = new ParameterizedThreadStart(Doit);//将函数作为参数传递到线程委托中
ths[m] = new Thread(pst[m]);//实例化线程
object o = "A";//将对象封装成Object
ths[m].Start(o);//传参数启动线程
}
public static void Doit(object Dom)
{
Console.WriteLine("A"+DateTime.Now);
string ml = "";
for (int i = 0; i < 10000; i++)
{
ml += DateTime.Now.ToString();
//Console.WriteLine(DateTime.Now);
}
Console.WriteLine(DateTime.Now);
}
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 7; i++)
{ Doit(); }
Console.WriteLine(sw.Elapsed);
sw.Restart();
Parallel.For(0, 7, i => Doit());
Console.WriteLine(sw.Elapsed);
Console.ReadKey();
}
static void Doit()
{
// Console.WriteLine("A" + DateTime.Now);
Int64 ml=0;
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j <100000; j++)
ml++;
//Console.WriteLine(DateTime.Now);
}
// Console.WriteLine(DateTime.Now);
}
}