下面我们就动手来创建一个线程,使用thread类创建线程时,只需提供线程入口即可。线程入口使程序知道该让这个线程干什么事,在c#中,线程入口是通过threadstart代理(delegate)来提供的,你可以把threadstart理解为一个函数指针,指向线程要执行的函数,当调用thread.start()方法后,线程就开始执行threadstart所代表或者说指向的函数。
打开你的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异常。
程序最后得到的结果将如下图:
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器