线程
class Program
{
static void Main(string[] args)
{
Thread backThread = new Thread(new ThreadStart(Worker));
backThread.IsBackground = true;
backThread.Start();
backThread.Join();
Console.WriteLine("从主线程退出");
Thread paramThread = new Thread(new ParameterizedThreadStart(Worker));
paramThread.Name = "线程1";
paramThread.Start("123");
}
public static void Worker()
{
Thread.Sleep(1000);
Console.WriteLine("从后台线程退出");
}
public static void Worker(object data)
{
Thread.Sleep(1000);
Console.WriteLine("传入的参数为{0}", data.ToString());
Console.WriteLine("{0}退出", Thread.CurrentThread.Name);
Console.Read();
}
}
线程池
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主线程ID={0}", Thread.CurrentThread.ManagedThreadId)
ThreadPool.QueueUserWorkItem(CallBackWorkItem)
ThreadPool.QueueUserWorkItem(CallBackWorkItem, "back")
Thread.Sleep(3000)
Console.WriteLine("线程退出")
}
public static void CallBackWorkItem(object state)
{
Console.WriteLine("线程池线程开始运行")
if (state != null)
{
Console.WriteLine("线程池线程ID为{0},传入的参数为{1}", Thread.CurrentThread.ManagedThreadId, state.ToString())
}
else
{
Console.WriteLine("线程池线程ID为{0}", Thread.CurrentThread.ManagedThreadId)
}
}
}
协作式取消线程池线程
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主线程运行");
CancellationTokenSource cts = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(CallBack, cts.Token);
Console.WriteLine("按下任意键取消操作");
Console.ReadKey();
cts.Cancel();
Console.ReadKey();
}
public static void CallBack(object state)
{
CancellationToken token = (CancellationToken)state;
Console.WriteLine("开始计数");
Count(token, 1000);
}
public static void Count(CancellationToken token, int countto)
{
for (int i = 0; i < countto; i++)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("计数取消");
return;
}
Console.WriteLine("计数为{0}", i);
Thread.Sleep(300);
}
Console.WriteLine("计数完成");
}
}
线程同步
class Program
{
static int tickets = 100;
static object gloalObj = new object();
static void Main(string[] args)
{
Thread thread1 = new Thread(SaleTicketThread1);
Thread thread2 = new Thread(SaleTicketThread2);
thread1.Start();
thread2.Start();
Console.ReadKey();
}
public static void SaleTicketThread1()
{
while (true)
{
lock (gloalObj)
{
if (tickets > 0)
{
Console.WriteLine("线程1出票:{0}", tickets--);
}
else
{
break;
}
}
}
}
public static void SaleTicketThread2()
{
while (true)
{
lock (gloalObj)
{
if (tickets > 0)
{
Console.WriteLine("线程2出票:{0}", tickets--);
}
else
{
break;
}
}
}
}
}