线程的定义构造函数有两种:
1.ThreadStart()
2.ParameterizedThreadStart()
ThreadStart 用于不带参数的并且无返回值的方法的抽象 ParameterThreadStart 是带object参数的方法的抽象
public class ThreadStartTest
{
//无参数的构造函数
Thread thread = new Thread(new ThreadStart(ThreadMethod));
//带有object参数的构造函数
Thread thread2 = new Thread(new ParameterizedThreadStart(ThreadMethodWithPara));
public ThreadStartTest()
{
//启动线程1
thread.Start();
//启动线程2
thread2.Start(new Parameter { paraName="Test" });
}
static void ThreadMethod()
{
//....
}
static void ThreadMethodWithPara(object o)
{
if (o is Parameter)
{
// (o as Parameter).paraName.............
}
}
}
public class Parameter
{
public string paraName { get; set; }
}
使得当前线程休眠(暂时停止执行millis毫秒)
thread.sleep(3000)
阻塞其他线程,自己执行
当NewThread调用Join方法的时候,MainThread就被停止执行,
直到NewThread线程执行完毕
thread.join()
多个线程依次执行例子:
public static void ThreadJoin2()
{
IList<Thread> threads = new List<Thread>();
for (int i = 0; i < 3; i++)
{
Thread t = new Thread(
new ThreadStart(
() =>
{
for (int j = 0; j < 10; j++)
{
if (j == 0)
Console.WriteLine("我是线层{0}, 完成计数任务后我会把工作权交换给其他线程", Thread.CurrentThread.Name);
else
{
Console.WriteLine("我是线层{0}, 计数值:{1}", Thread.CurrentThread.Name, j);
}
Thread.Sleep(1000);
}
}));
t.Name = "线程" + i;
//将线程加入集合
threads.Add(t);
}
foreach (var thread in threads)
{
thread.Start();
//每次按次序阻塞调用次方法的线程
thread.Join();
}
}
释放并终止调用线程
Thread.Abort();
Interrupt 方法将当前的调用该方法的线程处于挂起状态和Abort方法不同的是,被挂起的线程可以唤醒
thread.Interrupt();
Suspend 和Resume方法很奥妙,前者将当前运行的线程挂起,后者能够恢复当钱被挂起的线程
Thread.CurrentThread.Suspend();
thread.Resume(); |