下面的多线程源码,为什么每次执行出来的结果都不一样?///////////////////////////////////////////////////////////////////////
///描述:使用lock关键字
///////////////////////////////////////////////////////////////////////
using System;
using System.Threading;internal class Account
{
int balance;
Random r = new Random(); internal Account(int initial)
{
balance = initial;
} internal int Withdraw(int amount)
{
if (balance < 0)
{
throw new Exception("Negative Balance");
}
lock (this)
{
Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name+",balance:"+balance+",amount:"+amount); if (balance >= amount)
{
Thread.Sleep(5);
balance = balance - amount;
return amount;
}
else
{
return 0;
}
}
} internal void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(-50, 100));//要执行1000次吗?
}
}
}
internal class Test
{
static internal Thread[] threads = new Thread[10]; public static void Main()
{
Account acc = new Account(0); 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].Name = i.ToString();
} for(int i = 0; i <10; i++)
{
threads[i].Start();
} Console.ReadLine();
}
}
///描述:使用lock关键字
///////////////////////////////////////////////////////////////////////
using System;
using System.Threading;internal class Account
{
int balance;
Random r = new Random(); internal Account(int initial)
{
balance = initial;
} internal int Withdraw(int amount)
{
if (balance < 0)
{
throw new Exception("Negative Balance");
}
lock (this)
{
Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name+",balance:"+balance+",amount:"+amount); if (balance >= amount)
{
Thread.Sleep(5);
balance = balance - amount;
return amount;
}
else
{
return 0;
}
}
} internal void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(-50, 100));//要执行1000次吗?
}
}
}
internal class Test
{
static internal Thread[] threads = new Thread[10]; public static void Main()
{
Account acc = new Account(0); 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].Name = i.ToString();
} for(int i = 0; i <10; i++)
{
threads[i].Start();
} Console.ReadLine();
}
}
解决方案 »
- winform中如何播放flv视频?
- 使用MS chart控件作图,线条太细怎么调,求达人解
- 关于弹出对话框提示用户判断问题
- Fill 取数据为什么一直没反应。
- 关于多数据库查询疑问,140分再开一贴,顺便BS下SQL斑的!
- 重写窗体的Dispose和Form_closing事件效果是否一样?
- 请教如何在子窗体调用主窗体的axMSComm
- 该语句select max(to_number(vcEquipCode)) as vcEquipCode from gdequipmentcontentlf 是否正确?
- VS2010中的单元测试
- 关于C#标签的处理问题
- 100分求c#.net下水晶报表打印C1Flexgrid的例子
- Pointer.Box使用问题
Random r = new Random();
不是取随机数么?结果当然不一样了.
例如有按程序执行的顺序我觉得首先执行的应该是 threads[0],但是执行结果并不是这样的!10个线程都有可能最先执行!
我就是想问下为什么会出现这种情况?
Current Thread:0,balance:***,amount:***
....
....
我不知道你们运行过没?但是我感觉我已经说清楚了啊。
Thread.Sleep(5);
这会使线程睡眠5毫秒,,这5毫秒CPU可以处理其它的线程,包括你那其余的9个线程,或者系统线程或者其它应用程序线程...相同优先级的线程的思想没有谁先谁后的..比较狭义,但却可以实现同步...