using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
   7:  
namespace SynchronizationSamples
   9: {
class SharedState
  11:     {
int state = 0;
object();
int State 
  15:         { 
return state;}
value; }
  18:         }
  19:  
int IncrementState()
  21:         {
false;
ref lockTaken);
if (lockTaken)
  25:             {
try
  27:                 {
return ++state;
  29:                 }
finally
  31:                 {
  32:                     Monitor.Exit(syncRoot);
  33:                 }
  34:             }
else
  36:             {
return state;
  38:             }
  39:         }
  40:     }
  41:  
class Job
  43:     {
  44:         SharedState sharedState;
public Job(SharedState sharedState)
  46:         {
this.sharedState = sharedState;
  48:         }
  49:  
void DoTheJob()
  51:         {
int i = 0; i < 50000;i++ )
  53:             {
  54:                 sharedState.IncrementState();
  55:             }
  56:         }
  57:     }
class Program
  59:     {
string[] args)
  61:         {
int numTasks = 20;
new SharedState();
new Task[numTasks];
  65:  
int i = 0; i < numTasks; i++)
  67:             {
new Job(state).DoTheJob);
  69:                 tasks[i].Start();
  70:             }
  71:  
int i = 0; i < numTasks;i++ )
  73:             {
  74:                 tasks[i].Wait();
  75:             }
,state.State);
  77:             Console.Read();
  78:         }
  79:     }
  80: }

相关文章:

  • 2022-12-23
  • 2021-12-03
猜你喜欢
  • 2022-02-06
  • 2021-10-01
  • 2022-01-08
相关资源
相似解决方案