using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp9
{
class Program
{
static readonly Queue<int> rowQueue = new Queue<int>();
static object objLock = new object();
//读取队列
public static int GetRow()
{
int row = 0;
lock (objLock)
{
if (IsRowAvailable)
{
row = rowQueue.Dequeue();
}
return row;
}
}
//只读属性,确定队列中是不是还有元素
public static bool IsRowAvailable
{
get
{
return rowQueue.Count > 0;
}
}
static void Main(string[] args)
{
rowQueue.Clear();
for (int i = 0; i < 1000; i++) {
rowQueue.Enqueue(i);
}
Console.WriteLine("写入队列成功");
int num = 5;
var factory = new TaskFactory();
var tasks = new Task[num];
for (int i = 0; i < num; i++)
{
Task task = tasks[i];
task = factory.StartNew(() =>
{
Timer timer = new Timer((o) =>
{
if (IsRowAvailable)
{
int r = GetRow();
Console.WriteLine($"线程:{task.Id}取得值:{r}");
}
}, null,500, 1000);
});
}
Console.ReadLine();
}
}