连接线程
我们一般用Join方法。但一般让线程有序进行就可以排成一个委托链。
1.使用lock
2.加入名称空间,
3.加入名称空间,
4.在代码区添加:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ThreadTest
{
class Program
{
private static Thread th;
//private static Thread FirstThread;
//private static Thread SecondThread;
static void Main(string[] args)
{
//------------------------------------------------------------
// 连接线程
//------------------------------------------------------------
ThreadStart FirstStart = delegate
{
for (int i = 1; i < 250; i++)
{
Console.WriteLine(i);
}
};
ThreadStart SecondStart = delegate
{
// FirstThread.Join();
for (int i = 251; i < 500; i++)
{
Console.WriteLine(i);
}
};
ThreadStart start = FirstStart + SecondStart;
//FirstThread = new Thread(FirstStart);
//SecondThread = new Thread(SecondStart);
Thread thread = new Thread(start);
thread.Start();
//FirstThread.Start();
//FirstThread.Join();
//SecondThread.Start();
Console.Read();
}
}
}
另外,同步的几个选择:using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ThreadTest
{
class Program
{
private static Thread th;
//private static Thread FirstThread;
//private static Thread SecondThread;
static void Main(string[] args)
{
//------------------------------------------------------------
// 连接线程
//------------------------------------------------------------
ThreadStart FirstStart = delegate
{
for (int i = 1; i < 250; i++)
{
Console.WriteLine(i);
}
};
ThreadStart SecondStart = delegate
{
// FirstThread.Join();
for (int i = 251; i < 500; i++)
{
Console.WriteLine(i);
}
};
ThreadStart start = FirstStart + SecondStart;
//FirstThread = new Thread(FirstStart);
//SecondThread = new Thread(SecondStart);
Thread thread = new Thread(start);
thread.Start();
//FirstThread.Start();
//FirstThread.Join();
//SecondThread.Start();
Console.Read();
}
}
}
1.使用lock
2.加入名称空间,
using System.Runtime.CompilerServices;
然后再需要锁定的Method上添加:[MethodImpl(MethodImplOptions.Synchronized)]3.加入名称空间,
using System.EnterpriseServices;
在需要同步的类上面添加: [Synchronization(SynchronizationOption.Required)] 4.在代码区添加:
Monitor.Enter(this);
Monitor.Exit(this);
Monitor.Exit(this);