using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadDemo
{
class Program
{
static public List<int> temp = new List<int >();
static public List<Thread> worker = new List<Thread>();
static public List<List<int>> Temporary = new List<List<int>>();
static void Main(string[] args)
{
temp.add(20);
temp.add(10);
temp.add(5);
foreach (int k in temp)
{
int z = 0;
worker[z] = new Thread(() => { sample(k); });
worker[z].Name = "Worker" + z.ToString();
worker[z].Start();
z++;
}
}
public static void sample(int n)
{
List<int> local = new List<int>();
for (int i = 0; i < n; i++)
{
local.Add(i);
}
Temporary.Add(local);
}
}
}
在此程序中,当在主程序中启动foreach循环时,我在线程中遇到了问题,即创建了三个线程并同时启动了该线程。在该线程中,第一个线程的操作时间比其他线程长,因此将花费一些时间,但其他线程在第一个线程之前完成
由于此顺序在临时中被更改。我需要与临时列表顺序相同的临时列表顺序。如何使用线程来实现这一点
最佳答案
这是您的代码的快速入门:
class Program
{
static public List<int> temp = new List<int >();
static public List<Thread> worker = new List<Thread>();
static public List<List<int>> temporary = new List<List<int>>();
static public object sync = new object();
static void Main(string[] args)
{
temp.add(20);
temp.add(10);
temp.add(5);
// Add a corresponding number of lists
for( int i = 0; i < temp.Count; ++i)
{
temporary.Add(new List<int>);
}
// As Jon Skeet mentioned, z must be declared outside the for loop
int z = 0;
foreach (int k in temp)
{
// As Jon Skeet mentioned, you need to capture the value of k
int copy = k;
Thread t = new Thread(() => { Sample(copy, z); });
t.Name = "Worker" + z.ToString();
// set the thread to background, so your thread is
// properly closed when your application closes.
t.IsBackground = true;
t.Start();
// Calling worker[z] will always going to be out of bounds
// because you didn't add anything to to the worker list,
// therefore you just need to add the thread to the worker
// list. Note that you're not doing anything with the worker
// list, so you might as well not have it at all.
worker.Add(t);
z++;
}
}
// Supply the order of your array
public static void Sample(int n, int order)
{
for (int i = 0; i < n; i++)
{
// Technically in this particular case you don't need to
// synchronize, but it doesn't hurt to know how to do it.
lock(sync)
{
temporary[order].Add(i);
}
}
}
现在,临时列表应按正确的顺序包含其他列表(与您的tmp顺序相同)。您的标题中确实提到了计划,但是我不确定为什么您需要在这里进行计划,或者您到底想尝试了解什么。
关于c# - 线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3090472/