using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadSample
{
class Program
{
static void Main(string[] args)
{
int numThreads = 20;
ShareState state = new ShareState();
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new Thread(new Task(state).DoTheTask);
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
Console.WriteLine("ShareState.State最後結果是:" + state.State);
Console.ReadLine();
}
}
public class Task
{
ShareState shareState;
public Task(ShareState shareState)
{
this.shareState = shareState;
}
public void DoTheTask()
{
///設爲5000,數據大點更能 看到線程非安全的效果
for (int i = 0; i < 5000; i++)
{
shareState.State += 1;
}
}
}
public class ShareState
{
public int State { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadSample02
{
class Program
{
static void Main(string[] args)
{
int numThreads = 20;
ShareState state = new ShareState();
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new Thread(new Task(state).DoTheTask);
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
Console.WriteLine("ShareState.State最後結果是:" + state.State);
Console.ReadLine();
}
}
public class Task
{
ShareState shareState;
public Task(ShareState shareState)
{
this.shareState = shareState;
}
public void DoTheTask()
{
///設爲5000,數據大點更能 看到線程非安全的效果
for (int i = 0; i < 5000; i++)
{
lock (shareState)
{
shareState.State += 1;
}
}
}
}
public class ShareState
{
public int State { get; set; }
}
}