Advertisement
ivandrofly

Barrier - C#

Feb 26th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4.  
  5. namespace BarrierDemo
  6. {
  7.     class Account
  8.     {
  9.         public double Balance { get; set; }
  10.         public Account(double sum)
  11.         {
  12.             Balance = sum;
  13.         }
  14.         public int CalcCreaditPoint()
  15.         {
  16.             Thread.Sleep(400);
  17.             return (int)Balance / 10;
  18.         }
  19.         public double CalcUBalance(double currenty)
  20.         {
  21.             Thread.Sleep(400);
  22.             return currenty * Balance;
  23.         }
  24.     }
  25.     class Program
  26.     {
  27.         public static List<Account> accounts = new List<Account>();
  28.         public static Barrier myBarrier = new Barrier(3);
  29.         public static double balanceTotal = 0;
  30.         public static double creaditPointTotal = 0;
  31.         static void Main(string[] args)
  32.         {
  33.             CreateAccounts();
  34.             new Thread(CalculateAccountsTotal).Start();
  35.             new Thread(CalculateTotalCreditPoints).Start();
  36.             myBarrier.SignalAndWait();
  37.             Console.WriteLine("Total balance: " + balanceTotal);
  38.             Console.WriteLine("Total credit points: " + creaditPointTotal);
  39.             Console.ReadLine();
  40.         }
  41.  
  42.         private static void CalculateTotalCreditPoints(object obj)
  43.         {
  44.             double total = 0;
  45.             foreach (Account account in accounts)
  46.             {
  47.                 Thread.Sleep(500);
  48.                 total += account.CalcCreaditPoint();
  49.             }
  50.             creaditPointTotal = total;
  51.             myBarrier.SignalAndWait();
  52.         }
  53.  
  54.         private static void CalculateAccountsTotal()
  55.         {
  56.             double total = 0;
  57.             foreach (Account account in accounts)
  58.             {
  59.                 Thread.Sleep(500);
  60.                 total += account.Balance;
  61.             }
  62.             balanceTotal = total;
  63.             myBarrier.SignalAndWait();
  64.         }
  65.  
  66.         private static void CreateAccounts()
  67.         {
  68.             double[] sums = { 12000, 8000, 10000, -400, 5400, 8000, 2240 };
  69.             foreach (double sum in sums)
  70.             {
  71.                 accounts.Add(new Account(sum));
  72.                 Thread.Sleep(200);
  73.             }
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement