日期:2010-06-20 浏览次数:20497 次
看一下以下两个例子的运行结果:
//TestThread.cs
using System;using System.Threading;public class Test{ static int count=0; static void Main() { ThreadStart job = new ThreadStart(ThreadJob); Thread thread = new Thread(job); thread.Start(); for (int i=0; i < 5; i++) { count++; } thread.Join(); Console.WriteLine ("Final count: {0}", count); } static void ThreadJob() { for (int i=0; i < 5; i++) { count++; } }}
//InnerDataThread.cs
using System;using System.Threading;public class Test{ static int count=0; static void Main() { ThreadStart job = new ThreadStart(ThreadJob); Thread thread = new Thread(job); thread.Start(); for (int i=0; i < 5; i++) { int tmp = count; Console.WriteLine ("Read count={0}", tmp); Thread.Sleep(50); tmp++; Console.WriteLine ("Incremented tmp to {0}", tmp); Thread.Sleep(20); count = tmp; Console.WriteLine ("Written count={0}", tmp); Thread.Sleep(30); } thread.Join(); Console.WriteLine ("Final count: {0}", count); } static void ThreadJob() { for (int i=0; i < 5; i++) { int tmp = count; Console.WriteLine ("\t\t\t\tRead count={0}", tmp); Thread.Sleep(20); tmp++; Console.WriteLine ("\t\t\t\tIncremented tmp to {0}", tmp); Thread.Sleep(10); count = tmp; Console.WriteLine ("\t\t\t\tWritten count={0}", tmp); Thread.Sleep(40); } }}
Read count=0 Read count=0 Incremented tmp to 1 Written count=1Incremented tmp to 1Written count=1 Read count=1 Incremented tmp to 2Read count=1 Written count=2 Read count=2Incremented tmp to 2 Incremented tmp to 3Written count=2 Written count=3Read count=3 Read count=3Incremented tmp to 4 Incremented tmp to 4 Written count=4Written count=4 Read count=4Read count=4 Incremented tmp to 5 Written count=5Incremented tmp to 5Written count=5Read count=5Incremented tmp to 6Written count=6Final co |