多线程之搬运货物1:不分堆搬
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Move();
Console.ReadLine();
}
List<string> productList = new List<string>() { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE" };//货物
private void Move()
{
for(int i = 1; i<= 10;i++)
{
productList.Add(i.ToString());
}
ThreadPool.SetMaxThreads(10, 10);
lock (this)
{
while (productList.Count > 0)
{
lock (this)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(RealMove),productList[0]);
productList.RemoveAt(0);
}
}
}
}
private void RealMove(object product)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("货物" + product.ToString() + "已经被成功送达目的地!" + System.DateTime.Now.ToString());//YYYY-MM-DD HH-MM-mm
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Move();
Console.ReadLine();
}
List<string> productList = new List<string>() { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE" };//货物
private void Move()
{
for(int i = 1; i<= 10;i++)
{
productList.Add(i.ToString());
}
ThreadPool.SetMaxThreads(10, 10);
lock (this)
{
while (productList.Count > 0)
{
lock (this)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(RealMove),productList[0]);
productList.RemoveAt(0);
}
}
}
}
private void RealMove(object product)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("货物" + product.ToString() + "已经被成功送达目的地!" + System.DateTime.Now.ToString());//YYYY-MM-DD HH-MM-mm
}
}
}