Created
March 6, 2017 04:33
-
-
Save xbotter/fe83130576143dc77a457a5c311d4eef to your computer and use it in GitHub Desktop.
C#多线程处理示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var taskPool = new List<Task>(); | |
var seq = 1; | |
var stack = new Stack<int>(Enumerable.Range(0, 100).ToList()); | |
Enumerable.Range(0, 20) | |
.Select(_ => new Random(_).Next(600,900)) | |
.ToList().ForEach(_ => | |
{ | |
var num = seq++; | |
var task = Task.Run(() => | |
{ | |
while (stack.Count > 0) | |
{ | |
int t; | |
lock (stack) | |
{ | |
t = stack.Pop(); | |
} | |
Thread.Sleep(_); | |
Console.WriteLine(num.ToString() + " Thread Get "+ t.ToString() +" Wait " + _); | |
} | |
}); | |
taskPool.Add(task); | |
}); | |
Task.WaitAll(taskPool.ToArray()); | |
Console.WriteLine("Main Exit"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment