在thread1和thread2中创建多个线程 参考using System.Threading; Thread thread1 = new Thread(new ThreadStart(setDatagridview11)); Thread thread2 = new Thread(new ThreadStart(setDatagridview22)); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join();
时间: 2023-08-14 20:06:32 浏览: 169
1、动态线程的创建与删除.rar_RT thread 线程_rtthread和ccs_woolnfx_创建线程_线程创建
如果需要在 thread1 和 thread2 中创建多个线程,可以在 setDatagridview11 和 setDatagridview22 方法中使用 Thread 类来创建新线程。然后使用 Start 方法来启动新线程,并使用 Join 方法等待它们完成。
下面是一个示例代码:
```
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main thread started.");
Thread thread1 = new Thread(new ThreadStart(setDatagridview11));
Thread thread2 = new Thread(new ThreadStart(setDatagridview22));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Main thread finished.");
Console.ReadKey();
}
static void setDatagridview11()
{
Console.WriteLine("setDatagridview11 started.");
for (int i = 0; i < 5; i++)
{
Thread childThread = new Thread(new ParameterizedThreadStart(ChildThreadFunc));
childThread.Start(i);
}
Console.WriteLine("setDatagridview11 finished.");
}
static void setDatagridview22()
{
Console.WriteLine("setDatagridview22 started.");
for (int i = 0; i < 5; i++)
{
Thread childThread = new Thread(new ParameterizedThreadStart(ChildThreadFunc));
childThread.Start(i + 5);
}
Console.WriteLine("setDatagridview22 finished.");
}
static void ChildThreadFunc(object index)
{
Console.WriteLine("Child thread {0} started.", index);
Thread.Sleep(1000);
Console.WriteLine("Child thread {0} finished.", index);
}
}
```
在这个示例中,setDatagridview11 和 setDatagridview22 方法分别创建了 5 个新线程,并在其中调用了 ChildThreadFunc 方法。在 Main 方法中,启动 thread1 和 thread2 线程,并使用 Join 方法等待它们完成。运行程序后,你将会看到如下输出:
```
Main thread started.
setDatagridview11 started.
setDatagridview22 started.
Child thread 0 started.
Child thread 5 started.
Child thread 1 started.
Child thread 6 started.
Child thread 2 started.
Child thread 7 started.
Child thread 3 started.
Child thread 8 started.
Child thread 4 started.
Child thread 9 started.
Child thread 0 finished.
Child thread 5 finished.
Child thread 1 finished.
Child thread 6 finished.
Child thread 2 finished.
Child thread 7 finished.
Child thread 3 finished.
Child thread 8 finished.
Child thread 4 finished.
Child thread 9 finished.
setDatagridview11 finished.
setDatagridview22 finished.
Main thread finished.
```
阅读全文