我有 2 个线程(在打印机和计数器类中)。计数器类更新存储中的属性,打印机打印它。现在我只想按计数器打印更新的值一次。那么如何在打印最后一个更新的数字后停止执行我的打印机线程。它有时会打印最后一个数字一次或有时不止一次。基本上我需要更新一个属性,每次更新该属性时,我都需要在控制台上打印更新的值,并且打印机线程不知道将要发生的更新数量。所以它应该在更新线程停止更新时停止。
代码是这样的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Threads
{
class Storage
{
static int _number;
public readonly static object LockNumber = new object();
public static int Number
{
get
{
lock(LockNumber)
{
Monitor.Pulse(LockNumber);
return _number;
}
}
set
{
lock(LockNumber)
{
_number = value;
Monitor.Pulse(LockNumber);
Monitor.Wait(LockNumber);
}
}
}
}
class Counter
{
public Thread t = new Thread(new ThreadStart(CounterFunction));
public Counter()
{
t.Start();
}
public static void CounterFunction()
{
for (int i = 0; i < 25; i++)
{
Storage.Number = i;
}
}
}
class Printer
{
public Thread t1 = new Thread(new ThreadStart(Print));
public Printer()
{
t1.Start();
}
public static void Print()
{
while (true)
{
Console.WriteLine("Number is " + Storage.Number);
}
}
}
class Check
{
static void Main()
{
Storage s1 = new Storage();
Counter c = new Counter();
Printer p = new Printer();
c.t.Join();
if (!c.t.IsAlive)
{
p.t1.Abort();
}
Thread.Sleep(10000);
}
}
}