| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 563 人关注过本帖
标题:[求助]lock 是什么?
只看楼主 加入收藏
wsq1168
Rank: 1
等 级:新手上路
帖 子:72
专家分:0
注 册:2007-8-24
收藏
 问题点数:0 回复次数:1 
[求助]lock 是什么?

lock 是什么?
public void UseMultiThread2()
{
Console.WriteLine("Child Thread 2 Started");
Console.WriteLine("Child Thread 2 - Counting from 11 to 20");
for (int i = 11; i <= 20; i++)
{
for (int a = 0; a < 20; a++)
{
Console.Write(".");
}
Console.WriteLine(i);
}
Console.WriteLine("Child Thread 2 finished");

Monitor.Enter(this);
Console.WriteLine("Child Thread 2 Started");
Console.WriteLine("Child Thread 2 - Counting from 11 to 20");
for (int i = 11; i <= 20; i++)
{
for (int a = 0; a < 20; a++)
{
Console.Write(".");
}
Console.WriteLine(i);
}
Console.WriteLine("Child Thread 2 finished");
Monitor.Exit(this);

lock (this)
{
Console.WriteLine("Child Thread 2 Started");
Console.WriteLine("Child Thread 2 - Counting from 11 to 20");
for (int i = 11; i <= 20; i++)
{
for (int a = 0; a < 20; a++)
{
Console.Write(".");
}
Console.WriteLine(i);
}
Console.WriteLine("Child Thread 2 finished");
}
}

搜索更多相关主题的帖子: lock 
2007-09-22 12:39
jxnuwy04
Rank: 2
等 级:新手上路
威 望:4
帖 子:768
专家分:0
注 册:2006-9-15
收藏
得分:0 

以下转自MSDN
---------------------------------------
lock 确保当一个线程位于代码的临界区时,另一个线程不进入临界区。如果其他线程试图进入一个锁定代码,则它将在释放该对象前一直等待(块)。
下例使用线程和 lock。只要 lock 语句存在,语句块就是临界区并且 balance 永远不会是负数。
// statements_lock2.cs
using System;
using System.Threading;

class Account
{
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 (this)
{
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 Test
{
public static void Main()
{
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();
}
}
}


------------------不为别的,就为你,我的理想!-----------------
2007-09-22 13:16
快速回复:[求助]lock 是什么?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.045320 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved