最近遇到了多线程的问题,所以今天在这里总结一下:
首先,创建一个线程: Thread t1 = new Thread(ThreadStart);
这里t1是创建的线程变量,而ThreadStart是一个静态的没有返回值的方法即static void
而ThreadStart函数里面的内容就是具体该线程要执行的代码
然后 t1.Start();就是启动这个线程
这里附上我具体的代码:
static void Main(string[] args)
{
Thread t1 = new Thread(ThreadStart);
Thread t2 = new Thread(Treads);
t1.Start();
t2.Start();
{
Thread t1 = new Thread(ThreadStart);
Thread t2 = new Thread(Treads);
t1.Start();
t2.Start();
while(true)
{
DateTime nowTime = DateTime.Now;
if (nowTime.Millisecond == 0)
{
Console.WriteLine("计算天数据");
Thread.Sleep(100);
}
}
Console.ReadKey();
}
static void ThreadStart()
{
while(true)
{
DateTime nowTime = DateTime.Now;
if (nowTime.Millisecond == 0)
{
Console.WriteLine("计算小时数据");
Thread.Sleep(100);
}
}
}
static void Treads()
{
while (true)
{
{
DateTime nowTime = DateTime.Now;
if (nowTime.Millisecond == 0)
{
Console.WriteLine("计算天数据");
Thread.Sleep(100);
}
}
Console.ReadKey();
}
static void ThreadStart()
{
while(true)
{
DateTime nowTime = DateTime.Now;
if (nowTime.Millisecond == 0)
{
Console.WriteLine("计算小时数据");
Thread.Sleep(100);
}
}
}
static void Treads()
{
while (true)
{
DateTime nowTime = DateTime.Now;
if (nowTime.Millisecond == 0)
{
Console.WriteLine("计算月数据");
Thread.Sleep(100);
}
if (nowTime.Millisecond == 0)
{
Console.WriteLine("计算月数据");
Thread.Sleep(100);
}
}
}
}
下面是我的执行结果:
就是每隔一秒钟就执行一次,具体的时间间隔什么的可以改变,先写到这,等以后用到新的,再重新修改!