using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Thread newThread = new Thread(test); newThread.Start("para input"); newThread = new Thread(test); newThread.Start("para input"); } public static void test(object ob) { lock (ob) { Console.WriteLine("do something"); Thread.Sleep(5000); } } }}
输出结果为:首先输出 do something,过5秒后输出下一个do something.
using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Thread newThread = new Thread(test); newThread.Start("para input"); newThread = new Thread(test); newThread.Start("para output"); } public static void test(object ob) { lock (ob) { Console.WriteLine("do something"); Thread.Sleep(5000); } } }}
如果使用不同的参数,则不会实现互斥,两个输出语句do something同时出现。