c#中的多线程/并行处理
本文关键字:并行处理 多线程 | 更新日期: 2023-09-27 18:04:32
我有4个任务要完成使用多线程的概念。我有4个服务员。
如何分配空闲的女服务员来处理其中一项任务?
-I不断得到重复的数据(例如:4线程做类似的任务)-如果我使用锁,它锁定1个线程做4个任务,这不是我想要的
我代码: private void MTDemo()
{
String threadName = Thread.CurrentThread.Name;
while (true)
{
int numWaitingCustomer = 0;
Int32.TryParse(textBox1.Text, out numWaitingCustomer);
if (numWaitingCustomer > 0)
{
String takeOrderString = String.Format("Take order {0},{1}", threadName, numWaitingCustomer);
String serveMeal = String.Format("Serve meal {0},{1}",threadName, numWaitingCustomer);
String billCustomer = String.Format("Bill Customer {0},{1}", threadName, numWaitingCustomer);
String cleanTable = String.Format("Clean Table {0},{1}", threadName, numWaitingCustomer);
OutputMessage1(takeOrderString); Thread.Sleep(500);
OutputMessage1(serveMeal); Thread.Sleep(500);
OutputMessage1(billCustomer); Thread.Sleep(500);
OutputMessage1(cleanTable); Thread.Sleep(500);
numWaitingCustomer--;
SetControlPropertyValue(textBox1, "text", numWaitingCustomer.ToString());
}
}
}
让每个线程循环遍历任务列表并完成第n个任务,因此服务员1将完成任务0,4,8…完成任务1、5、9……等。
for(int i = threadNumber; i < taskList.length-threadNumber; i = i*totalThreads+ThreadNumber) {
...
}