Code
using System;
using System.Threading;
using System.Collections;
namespace MultiThreadLearn
{
internal class Account
{
int balance;
Random r = new Random();
internal Account(int initial)
{
balance = initial;
}
internal int Withdraw(int amount)
{
try
{
if (balance < 0)
{
throw new Exception("Negative Balance");
}
lock (this) //如果没有lock,可能会出现负值
{
Console.WriteLine("可用余额:" + balance);
if (balance >= amount)
{
balance = balance - amount;
Console.WriteLine("你已经取了:" + amount + ",可用余额为:" + balance + "。交易成功!");
Console.WriteLine();
return amount;
}
else
{
Console.WriteLine("你要取" + amount + "元,但是你的可用余额为" + balance + "。交易失败!");
Console.WriteLine();
return 0;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
internal void DoTransactions()
{
for (int i = 0; i < 2; i++) //每个线程取两次款
{
int ri =r.Next(100,200);
Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name);
Console.WriteLine("第"+(i+1)+"次交易");
Console.WriteLine("要取的金额是:"+ri);
Withdraw(ri);
}
}
}
internal class Test
{
static internal Thread[] threads = new Thread[10];
public static void Main2()
{
Account acc = new Account(700); //如果在初始化金额时,传了负值,会抛出异常,并输出
for (int i = 0; i < 3; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
threads[1].Priority = ThreadPriority.Highest;//如果不设,第一个输出的是线程0
for (int i = 0; i < 3; i++)
{
threads[i].Name = i.ToString();
}
for (int i = 0; i < 3; i++)
{
threads[i].Start();
}
Console.ReadLine();
}
}
}
using System;
using System.Threading;
using System.Collections;
namespace MultiThreadLearn
{
internal class Account
{
int balance;
Random r = new Random();
internal Account(int initial)
{
balance = initial;
}
internal int Withdraw(int amount)
{
try
{
if (balance < 0)
{
throw new Exception("Negative Balance");
}
lock (this) //如果没有lock,可能会出现负值
{
Console.WriteLine("可用余额:" + balance);
if (balance >= amount)
{
balance = balance - amount;
Console.WriteLine("你已经取了:" + amount + ",可用余额为:" + balance + "。交易成功!");
Console.WriteLine();
return amount;
}
else
{
Console.WriteLine("你要取" + amount + "元,但是你的可用余额为" + balance + "。交易失败!");
Console.WriteLine();
return 0;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
internal void DoTransactions()
{
for (int i = 0; i < 2; i++) //每个线程取两次款
{
int ri =r.Next(100,200);
Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name);
Console.WriteLine("第"+(i+1)+"次交易");
Console.WriteLine("要取的金额是:"+ri);
Withdraw(ri);
}
}
}
internal class Test
{
static internal Thread[] threads = new Thread[10];
public static void Main2()
{
Account acc = new Account(700); //如果在初始化金额时,传了负值,会抛出异常,并输出
for (int i = 0; i < 3; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
threads[1].Priority = ThreadPriority.Highest;//如果不设,第一个输出的是线程0
for (int i = 0; i < 3; i++)
{
threads[i].Name = i.ToString();
}
for (int i = 0; i < 3; i++)
{
threads[i].Start();
}
Console.ReadLine();
}
}
}