lock.cs

来自「.NET的课件。还不全。。后续我还会传上来的」· CS 代码 · 共 44 行

CS
44
字号
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) {
		lock (this)	{
			Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name + "balance = " + balance);
			if (balance >= amount) {
				Thread.Sleep(5);
				balance = balance - amount;
				return balance;
			}
			else {
				return 0; 
			}
		}
	}
	internal void DoTransactions() {
		for (int i = 0; i < 100; i++) {
			Withdraw(r.Next(-50, 100));
		}
	}
}
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();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?