发布网友 发布时间:2024-10-01 02:36
共1个回答
热心网友 时间:2024-10-01 04:36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading ;
namespace 多线程
{
class Program
{
Thread thread1 = null;
Thread thread2 = null;
Mutex mutex = null;
public static void Main()
{
//Monitor类的使用
//lock语句其实后台解析为Monitor类的调用
//Enter方法一直等待获得锁定的对象
//Exit方法是接触锁定
//一次只能有一个线程成为对象锁定的拥有者,只要解除了锁定,就进入了同步代码段。
//显示使用这个类的好处理,可以用try catch,如果出现异常,也可以保证正常的解除锁定
Program p = new Program();
p.RunThread();
Console.ReadLine();
}
public Program()
{
mutex = new Mutex() ;
thread1 = new Thread( new ThreadStart( Thread1Func ) ) ;
thread2 = new Thread( new ThreadStart( Thread2Func ) ) ;
}
public void RunThread()
{
thread1.Start() ;
thread2.Start() ;
}
private void Thread1Func()
{
for (int count = 0; count < 10; count++)
{
TestFunc("线程1 运行第 " + count.ToString() + " 次") ;
Thread.Sleep( 30 ) ;
}
}
private void Thread2Func()
{
for (int count = 0; count < 10; count++)
{
TestFunc(" 线程2 运行第 " + count.ToString() + " 次");
Thread.Sleep( 100 ) ;
}
}
private void TestFunc( string str)
{
Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString() );
Thread.Sleep(50);
}
}
}