2016-12-17
无意间看到了关于C#线程的讲解。经过一下午的学习后,慢慢的对线程也有了一定的理解。这里讲解的是最基础的内容,包括线程的创建、睡眠、等待、终止。
实验环境:Visual studio 2010.
使用语言:C#
内容:创建、睡眠、等待、中止线程
1.创建新线程对象 Thread t=new Thread();
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace 线程学习
{
class Program
{
static void PrintNumbers()
{ Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Console.WriteLine(i);
}
} static void Main(string[] args)
{
Thread t = new Thread(PrintNumbers);
t.Start();
PrintNumbers();
}
}
}
通过Thread t=new Thread创建新对象后,t为子线程,t.Start()开始执行子线程,子线程执行构造对象中的PrintNumber()函数,父线程执行下一行的PrintNumbers()函数,两线程并发,所以结果不定。
2.线程睡眠 调用Slee()函数,选择让线程暂时“睡眠“
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace 线程学习
{
class Program
{
static void PrintNumbers()
{
Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Console.WriteLine(i+"父线程");
}
}
static void PrintNumbersWithDelay()
{
Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Thread.Sleep(TimeSpan.FromSeconds());
Console.WriteLine(i+"子线程");
}
} static void Main(string[] args)
{
Thread t = new Thread(PrintNumbersWithDelay);
t.Start();
PrintNumbers();
}
}
}
创建线程后,子线程t执行PrintNumbersWithDelay()函数,其中每循环一次就睡眠一秒,父线程执行下一行的PrintNumbers()函数,两线程并发执行。
3.线程等待 调用join()函数,让线程按照想要的顺序执行
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 线程学习
{
class Program
{
static void PrintNumberWithDelay()
{
Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Thread.Sleep(TimeSpan.FromSeconds());
Console.WriteLine(i);
}
}
static void PrintNumbers()
{
Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Console.WriteLine(i);
}
}
static void Main(string[] args)
{
Console.WriteLine("Starting...");
Thread t = new Thread(PrintNumberWithDelay);
t.Start();
t.Join();
PrintNumbers();
Console.WriteLine("Thread completed");
}
}
}
创建线程后,t.join()之后的语句(即父线程)必须等待之前的语句执行完后,才能执行。
4.线程终止 调用Abort()函数,杀死该线程。
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 线程学习
{
class Program
{
static void PrintNumbers()
{
Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Console.WriteLine(i);
}
}
static void PrintNumberWithDelay()
{
Console.WriteLine("Starting...");
for (int i = ; i < ; i++)
{
Console.WriteLine(i);
Thread.Sleep(TimeSpan.FromSeconds()); }
} static void Main(string[] args)
{
Console.WriteLine("Starting Program..");
Thread t = new Thread(PrintNumberWithDelay);
t.Start();
t.Abort();
Console.WriteLine("A thread has been aborted");
t = new Thread(PrintNumbers);
t.Start();
PrintNumbers();
}
}
}
使用Abort()结束子线程。后面的代码跟前面例一类似