打开你的vs.net,新建一个控制台应用程序(console application),下面这些代码将让你体味到完全控制一个线程的无穷乐趣!
//threadtest.cs
using system;
using system.threading;
namespace threadtest
{
public class alpha
{
public void beta()
{
while (true)
{
console.writeline(alpha.beta is running in its own thread.);
}
}
};
public class simple
{
public static int main()
{
console.writeline(thread start/stop/join sample);
alpha oalpha = new alpha();
//这里创建一个线程,使之执行alpha类的beta()方法
thread othread = new thread(new threadstart(oalpha.beta));
othread.start();
while (!othread.isalive);
thread.sleep(1);
othread.abort();
othread.join();
console.writeline();
console.writeline(alpha.beta has finished);
try
{
console.writeline(try to restart the alpha.beta thread);
othread.start();
}
catch (threadstateexception)
{
console.write(threadstateexception trying to restart alpha.beta. );
console.writeline(expected since aborted threads cannot be restarted.);
console.readline();
}
return 0;
}
}
}
这段程序包含两个类alpha和simple,在创建线程othread时我们用指向alpha.beta()方法的初始化了threadstart代理(delegate)对象,当我们创建的线程othread调用othread.start()方法启动时,实际上程序运行的是alpha.beta()方法:
alpha oalpha = new alpha();
thread othread = new thread(new threadstart(oalpha.beta));
othread.start();
然后在main()函数的while循环中,我们使用静态方法thread.sleep()让主线程停了1ms,这段时间cpu转向执行线程othread。然后我们试图用thread.abort()方法终止线程othread,注意后面的othread.join(),thread.join()方法使主线程等待,直到othread线程结束。你可以给thread.join()方法指定一个int型的参数作为等待的最长时间。之后,我们试图用thread.start()方法重新启动线程othread,但是显然abort()方法带来的后果是不可恢复的终止线程,所以最后程序会抛出threadstateexception异常
以上就是c#的多线程机制初探(2)的内容。
