- 由于多线程只能执行无参或单参的方法,而多重循环需要一次性传入两个或两个以上的参数,因此,可以创建一个类型用于存储多重循环的参数,执行方法时传入该类型的对象,即可实现一次性传入多个参数。
- 线程并不是越多越好,要根据计算机的CPU和内存控制线程的数量。
- 可以设置全局变量控制线程的数量,在开辟线程前利用死循环实现主线程的阻塞,当线程数量小于给定值时才开辟新的线程,在线程方法执行完毕后设置线程数量减1即可。
- 可以设置全局变量判断多重循环是否执行完毕,在线程方法执行完毕后设置完成数量加1即可。
- 注意!多线程调用的方法中尽量使用局部变量,操作成员变量时注意线程安全问题。
using System;
using System.Threading;
namespace _02
{
class Program
{
public static int threadCount = 0;
public static int completeCount = 0;
static void Main(string[] args)
{
Console.WriteLine("*****多线程完成循环*****");
DateTime start = DateTime.Now;
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
while (true)
{
if (threadCount < 3)
{
break;
}
}
threadCount++;
new Thread(new ParameterizedThreadStart(ExecuteMethod)).Start(new Index(i, j));
}
}
while (true)
{
if (completeCount == 9)
{
break;
}
}
Console.WriteLine(DateTime.Now - start);
Console.WriteLine();
Console.WriteLine("*****单线程完成循环*****");
start = DateTime.Now;
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
ExecuteMethod(new Index(i, j));
}
}
Console.WriteLine(DateTime.Now - start);
Console.WriteLine();
}
public static void ExecuteMethod(object o)
{
Index index = (Index)o;
for (int i = 0; i < 2e9; i++)
{
i++;
}
Console.WriteLine($"{
index.i} * {
index.j} = {
index.i * index.j}");
completeCount++;
threadCount--;
}
}
class Index
{
public int i;
public int j;
public Index(int i, int j)
{
this.i = i;
this.j = j;
}
}
}
