作者powertodream (The Beginning)
看板C_Sharp
标题Re: [问题] 请教thread问题
时间Mon Aug 4 23:56:51 2008
※ 引述《kenshinn (子凌(b))》之铭言:
: ※ 引述《missbus (smile)》之铭言:
: 前文述删
: 看了阁下的程式後
: 关键在於
: new Thread(new ThreadStart(new hello(1).add)).Start();
: new Thread(new ThreadStart(new hello(2).add)).Start();
: 使得两条 Thread 以一前一後的方式开始执行
: 接着在 Add 方法中
: public void add()
: {
: for (int k = 0; k < 10; k++)
: {
: lock (this)
^^^^
不太了解为什麽要用this, 这样好像每个this的东西不一样.
可以试着在你的 class hello 里面宣告一个
static object locker = new object();
然後使用lock(locker)
应该可以达到你要的目的.
: {
: test.hello[1, 1] += 1;
: Console.WriteLine("hello object " + i + " -- " +
: Thread.CurrentContext.ToString() +
: " -- " + test.hello[1, 1]);
: }
: }
: }
: 虽然有 lock 但是两条 Thread 并行的结果,使得在离开 lock 後另一条 Thread 的
: 函式有机可趁,故结果是无法预测的
--
If people do not believe that mathematics is simple,
it is because they do not realize how complicated life is.
-- John Louis von Neumann
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.133.58.208
1F:→ powertodream:而且lock 要放在for外面. 08/04 23:58