您的位置:首页 > 编程语言 > C#

C#线程与线程池的使用

2010-10-23 21:25 435 查看
using System;
using System.Threading;
class ThreadTest
{

public static void Main(){

MyThread mt=new MyThread();

//Thread t0=new Thread(new ThreadStart(method1));
//Thread t1=new Thread(new ThreadStart(method2));
//Thread t2=new Thread(new ThreadStart(mt.method3));
//t0.Start();
//t1.Start();
//t2.Start();
//以上注释掉的就是正常线程创建与使用的方法
//以下是使用线程池进行系统自动管理后台线程

ThreadPool.QueueUserWorkItem(new WaitCallback(method1));
ThreadPool.QueueUserWorkItem(new WaitCallback(method2));
ThreadPool.QueueUserWorkItem(new WaitCallback(mt.method3));
//因为线程池创造线程属于守护线程,前台停止自然后台也停止,所以
//使用ReadLine()阻塞,查看结果
Console.ReadLine();

}
public static void method1(Object stateInfo){
//使用线程池必备参数Object
//没有这个参数使用线程池编译不过,应该是发送前台消息的一个参数
for(int i=0;i<1000;i++)
{
Console.Write("a");

Thread.Sleep(10);
}

}
public static void method2(Object stateInfo){
for(int i=0;i<1000;i++){

Console.Write("b");
Thread.Sleep(10);
}

}
}

class MyThread{

public void method3(Object stateInfo){

for(int i=0;i<1000;i++){
Console.Write("C");
}
}
}本文出自 “Haley笔记” 博客,请务必保留此出处http://haley.blog.51cto.com/2280460/409839
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐