扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
using namespace System; using namespace System::Threading; int main() { /*1*/ MessageBuffer^ m = gcnew MessageBuffer; /*2a*/ ProcessMessages^ pm = gcnew ProcessMessages(m); /*2b*/ Thread^ pmt = gcnew Thread(gcnew ThreadStart(pm,&ProcessMessages::ProcessMessagesEntryPoint)); /*2c*/ pmt->Start(); /*3a*/ CreateMessages^ cm = gcnew CreateMessages(m); /*3b*/ Thread^ cmt = gcnew Thread(gcnew ThreadStart(cm, &CreateMessages::CreateMessagesEntryPoint)); /*3c*/ cmt->Start(); /*4*/ cmt->Join(); /*5*/ pmt->Interrupt(); /*6*/ pmt->Join(); Console::WriteLine("Primary thread terminating"); } public ref class MessageBuffer { String^ messageText; public: void SetMessage(String^ s) { /*7*/ Monitor::Enter(this); messageText = s; /*8*/ Monitor::Pulse(this); Console::WriteLine("Set new message {0}", messageText); Monitor::Exit(this); } void ProcessMessages() { /*9*/ Monitor::Enter(this); while (true) { try { /*10*/ Monitor::Wait(this); } catch (ThreadInterruptedException^ e) { Console::WriteLine("ProcessMessage interrupted"); return; } Console::WriteLine("Processed new message {0}", messageText); } Monitor::Exit(this); } }; public ref class CreateMessages { MessageBuffer^ msg; public: CreateMessages(MessageBuffer^ m) { msg = m; } void CreateMessagesEntryPoint() { for (int i = 1; i <= 5; ++i) { msg->SetMessage(String::Concat("M-", i.ToString())); Thread::Sleep(2000); } Console::WriteLine("CreateMessages thread terminating"); } }; public ref class ProcessMessages { MessageBuffer^ msg; public: ProcessMessages(MessageBuffer^ m) { msg = m; } void ProcessMessagesEntryPoint() { msg->ProcessMessages(); Console::WriteLine("ProcessMessages thread terminating"); } }; |
Set new message M-1 Processed new message M-1 Set new message M-2 Processed new message M-2 Set new message M-3 Processed new message M-3 Set new message M-4 Processed new message M-4 Set new message M-5 Processed new message M-5 CreateMessages thread terminating ProcessMessage interrupted ProcessMessages thread terminating Primary thread terminating |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者