Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions homework.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -32,6 +32,24 @@ public async Task UpdateInventoryAsync(string title, int quantity)

// TODO: 使用 lock 语句保证线程安全
// 提示:在 lock 块中查找书籍并更新库存,若库存不足则输出提示
lock(_lock)
{
Book book = _books.Find(bk => bk.Title == title);
if (book == null)
{
Console.WriteLine($"错误:未找到书籍《{title}》。");
return;
}
if (book.Inventory >= quantity)
{
book.Inventory -= quantity;
Console.WriteLine($"成功购买《{title}》{quantity}册,购买后库存:{book.Inventory}。");
}
else
{
Console.WriteLine($"购买失败《{title}》{quantity}册,库存不足!当前库存:{book.Inventory}。");
}
}
}
}

Expand All @@ -42,6 +60,7 @@ public class BookStore
// TODO: 实现异步购书方法CheckoutAsync,调用 UpdateInventoryAsync
public async Task CheckoutAsync(string bookTitle, int quantity)
{
await _db.UpdateInventoryAsync(bookTitle, quantity);
}

public async Task SimulateMultipleUsers()
Expand All @@ -59,9 +78,13 @@ public async Task SimulateMultipleUsers()
// 提示:创建多个 Task 调用 CheckoutAsync,并传入不同书名和数量
var tasks = new List<Task>
{

CheckoutAsync("C#入门", 2),
CheckoutAsync("C#入门", 3),
CheckoutAsync("异步编程", 1),
CheckoutAsync("异步编程", 2),
CheckoutAsync("异步编程", 3)
};

await Task.WhenAll(tasks);

Console.WriteLine("\n购买后库存:");
books = await _db.GetBooksAsync();
Expand Down