关于线程和多线程和定时器
//线程
public class MyProccess
{
public void Start()
{
ThreadStart start=new ThreadStart(ThreadAction);
Thread th=new Thread(start);
th.IsBackground = true;
th.Start();
}
public void ThreadAction()
{
while (true)
{
try
{
//do something
System.Threading.Thread.Sleep(30000);
}
catch (Exception)
{
throw;
}
}
}
}
//多线程
static void MyMain()
{
WaitCallback callBack;
callBack = new WaitCallback(PooledFunc);
WaitCallback callBack2;
callBack2 = new WaitCallback(PooledFunc2);
WaitCallback callBack3;
callBack3 = new WaitCallback(PooledFunc3);
ThreadPool.QueueUserWorkItem(callBack,
"Is there any screw left?");
Console.WriteLine("Main thread. Is pool thread: {0}, Hash: {1}", Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode());
ThreadPool.QueueUserWorkItem(callBack2);
Console.WriteLine("Main thread. Is pool thread: {0}, Hash: {1}", Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode());
ThreadPool.QueueUserWorkItem(callBack3,
"Decrease stock of monkey wrench");
Console.WriteLine("Main thread. Is pool thread: {0}, Hash: {1}",Thread.CurrentThread.IsThreadPoolThread,Thread.CurrentThread.GetHashCode());
Console.ReadLine();
}
static void PooledFunc(object state)
{
while (true)
{
Console.WriteLine("Processing request ‘{0}‘." +" Is pool thread: {1}, Hash: {2}",(string)state, Thread.CurrentThread.IsThreadPoolThread,Thread.CurrentThread.GetHashCode());
// Simulation of processing time
Thread.Sleep(10000);
}
Console.WriteLine("Request processed");
}
static void PooledFunc2(object state)
{
while (true)
{
Console.WriteLine("Processing request How much is a 40W bulb?." + " Is pool thread: {0}, Hash: {1}", Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode());
// Simulation of processing time
Thread.Sleep(5000);
}
Console.WriteLine("Request processed");
}
static void PooledFunc3(object state)
{
while (true)
{
Console.WriteLine("Processing request This is PooledFunc3." + " Is pool thread: {0}, Hash: {1}", Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode());
// Simulation of processing time
Thread.Sleep(9000);
}
Console.WriteLine("Request processed");
}
多线程就相当于自己写好函数 委托给系统的线程池帮忙照顾
线程就是自己创建 添加委托 启动
定时器我的理解是 算是又一次封装的线程?
—————————————————————————————————————————————
补充,线程池
while(start)
{
if(flg)
{
Thread.Sleep(100);
}
}
修改flg 是否暂停
线程结束,线程池会释放
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。