做成一个线程阻塞的队列就可以了,
其实做队列都不用的
使用信号灯,做一个资源锁就可以了.using System;
using System.Collections.Generic;
using System.Text;using System.Threading;namespace BBRD_LOCK
{
public class BBRD_LOCK
{
private AutoResetEvent m_AutoResetEvent = new AutoResetEvent(false);
private int m_mount;
private int m_timeout;
public BBRD_LOCK(int mount,int timeout)
{
m_mount = mount;
m_timeout = timeout;
}
public bool Wait()
{
--m_mount;
if (m_mount < 0)
return this.Hold();
return true;
}
public void Signal()
{
++m_mount;
if (m_mount <= 0)
this.Release();
}
public bool Hold()
{
return m_AutoResetEvent.WaitOne(m_timeout);
} public void Release()
{
m_AutoResetEvent.Set();
}
}
}做好之后用了个测试程序,测试通过.using System;
using System.Collections.Generic;
using System.Text;namespace lockTest
{
class Program
{
static BBRD_LOCK.BBRD_LOCK m_Lock = new BBRD_LOCK.BBRD_LOCK(1,1000);
static int n = 0;
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(threadprocess));
thread.Start(i);
}
} static void threadprocess(object ob)
{
Random r = new Random();
while (true)
{
if(m_Lock.Wait())
{
Console.Write(ob.ToString() + " thread HOLD\t");
}
else
{
Console.Write("\n" + ob.ToString() + " thread HOLD false\n");
continue;
}
Console.Write(++n);
System.Threading.Thread.Sleep(r.Next(0,2000)); m_Lock.Signal();
Console.WriteLine("\t" + ob.ToString() + " thread Released\n"); }
}
}
}
其实做队列都不用的
使用信号灯,做一个资源锁就可以了.using System;
using System.Collections.Generic;
using System.Text;using System.Threading;namespace BBRD_LOCK
{
public class BBRD_LOCK
{
private AutoResetEvent m_AutoResetEvent = new AutoResetEvent(false);
private int m_mount;
private int m_timeout;
public BBRD_LOCK(int mount,int timeout)
{
m_mount = mount;
m_timeout = timeout;
}
public bool Wait()
{
--m_mount;
if (m_mount < 0)
return this.Hold();
return true;
}
public void Signal()
{
++m_mount;
if (m_mount <= 0)
this.Release();
}
public bool Hold()
{
return m_AutoResetEvent.WaitOne(m_timeout);
} public void Release()
{
m_AutoResetEvent.Set();
}
}
}做好之后用了个测试程序,测试通过.using System;
using System.Collections.Generic;
using System.Text;namespace lockTest
{
class Program
{
static BBRD_LOCK.BBRD_LOCK m_Lock = new BBRD_LOCK.BBRD_LOCK(1,1000);
static int n = 0;
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(threadprocess));
thread.Start(i);
}
} static void threadprocess(object ob)
{
Random r = new Random();
while (true)
{
if(m_Lock.Wait())
{
Console.Write(ob.ToString() + " thread HOLD\t");
}
else
{
Console.Write("\n" + ob.ToString() + " thread HOLD false\n");
continue;
}
Console.Write(++n);
System.Threading.Thread.Sleep(r.Next(0,2000)); m_Lock.Signal();
Console.WriteLine("\t" + ob.ToString() + " thread Released\n"); }
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货