test delegate


    class Program
    {

        private delegate string getastring();
        static void Main(string[] args)
        {
           
            int x = 40;
           // getastring firstmethod = new getastring(x.ToString);
            getastring firstmethod = x.ToString;
            Console.WriteLine("String is {0}",x.ToString());
            Console.WriteLine("String is {0}", firstmethod());

            Console.ReadLine();
        }

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;




namespace Test
{

     
      class Account
      {
          private Object thisLock = new Object();
          int balance;
 
          Random r = new Random();
 
          public Account(int initial)
          {
              balance = initial;
          }
 
          int Withdraw(int amount)
          {
 
              // This condition will never be true unless the lock statement
 
              // is commented out:
 
              if (balance < 0)
              {
                  throw new Exception("Negative Balance");
              }
 
              // Comment out the next line to see the effect of leaving out
 
              // the lock keyword:

              lock (thisLock)
              {
                  if (balance >= amount)
                  {
                      Console.WriteLine("Balance before Withdrawal :  " + balance);
                      Console.WriteLine("Amount to Withdraw        : -" + amount);
                      balance = balance - amount;
                      Console.WriteLine("Balance after Withdrawal  :  " + balance);
                      return amount;
                  }
                  else
                  {
                      return 0; // transaction rejected
 
                  }
             }
          }
 
          public void DoTransactions()
          {
              for (int i = 0; i < 100; i++)
              {
                  Withdraw(r.Next(1, 100));
              }
          }
      }


    class Program
    {


        static void Main(string[] args)
        {

            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }


        }
    }
}

posted @ 2017-02-16 09:29  微笑的''80  阅读(98)  评论(0)    收藏  举报