for (int i = 0; i < 10; i++)
{
new Thread(
delegate()
{
//MyCode;
}
).Start(); }
//怎么让循环中的线程按照I的顺序先后执行,是用Lock锁吗?
//应该怎么锁,请大侠指点
{
new Thread(
delegate()
{
//MyCode;
}
).Start(); }
//怎么让循环中的线程按照I的顺序先后执行,是用Lock锁吗?
//应该怎么锁,请大侠指点
解决方案 »
- DataGridView显示小问题
- 如何格式化后,取2位的有效值,,,,
- skinfeature界面换肤组件不错啊。效果比suipack好多了。
- 新手提问,具体如何显示数据库中的数据?
- 请问怎样用C#编程画类图,有什么主要的编程接口
- 为什么我制作安装时,加入自定义操作后快捷方式的执行结果是重新安装,而不加入自定义操作时,一切正常!
- C#里在线程里如何向主窗体过程发送消息?
- WebBrowser如何获取当前页面的html
- 大神们,帮帮忙啊,必须声明标量变量 "@username"
- 哪里有一个完整的例子,麻雀虽小,五脏俱全的,谁能说几句关于完整项目的统筹思想??
- listbox保存数据库问题?
- ListBox
一个一个顺序的执行
以此类推 不就行了吗
第一个线程控制 k=1
第二个线程当 k =1时执行貌似C# 中有这样的方法 能直接用的!
{
int order = 0;//, -1 for exit , 0 for initialize
int ordermax = 0;//最大编号
ParameterizedThreadStart threadProc = p =>
{
if (!(p is int)) return;
int myOrder = (int)p;
object sync = new object();
while (true)
{
lock (sync)//同步线程
{
if (order != myOrder)//判断状态机当前状态是否是到自己执行
{
Thread.Sleep(50);//阻塞自己线程50毫秒后继续下一次检测
continue;
}
Console.WriteLine(p);//实际操作
order++;//在lock块中,安全的操作状态
if (order > ordermax) order = 1;//循环状态
}
Thread.Sleep(50);
}
};
new Thread(threadProc).Start(1);//启动1个线程,编号1
new Thread(threadProc).Start(2);//启动1个线程,编号2
new Thread(threadProc).Start(3);//启动1个线程,编号3
new Thread(threadProc).Start(4);//启动1个线程,编号4
ordermax = 4;//最大值4
order = 1;//当前状态1,开始启动
Console.ReadKey();
}
for (int i = 0; i < 10; i++)
{
Action a = delegate()
{
//MyCode;
}; if (t != null)
t = t.ContinueWith(a);
else
t = Task.Factory.StartNew(a);
}
public const int Repetitions = 10000; public static void Main()
{
//Thread thread = new Thread(DoWork);
//thread.Start(".");
//thread.Join();
//for (int count = 0; count < Repetitions; count++)
//{
// Console.Write('-');
//}
Thread thread;
for (int i = 0; i < 3; i++)
{
thread = new Thread(DoWork);
if (i == 0)
{
thread.Start(".");
}
else if (i == 1)
{
thread.Start("-");
}
else if (i == 2)
{
thread.Start("*");
}
else {
thread.Start("&");
}
thread.Join();
}
Console.ReadLine();
} public static void DoWork(object state)
{
for (int count = 0; count < Repetitions; count++)
{
Console.Write(state);
}
}
}
一旦线程启动,就可以通过调用thread.Join()来造成一个“等待完成”(wait for completion)情形。调用线程会一直等待,直到thread实例终止。
delegate()
{
//MyCode;
}
).Start();改成这样 然后加一句
t.Join();
就可以了但是如果是这样 那你为什么不做一个方法呢? 让那个方法循环执行 线程里的方法?
搞那么多线程看的都麻烦