如下,新建一个C#控制台应用程序,且在main方法中新建两个线程,分别调用两个方法:

method1(),method2(),method1()用于执行一个循环,值为1-1000000000,method2()用于监听键盘输入,当输入A-Z任意键时循环暂停,按空格键循环继续,按Esc循环退出,应用程序终止,现在method1()和method2()我已经完成了,剩下的就是线程调用的问题了,已经实现了按任意键停止,但是不能继续,求高手帮忙解答,最好给段简短的代码。

慕婉清6462132
浏览 196回答 1
1回答

哈士奇WWW

使用Thread的Suspend方法可以暂停一个线程,Resume继续,给你写个例子吧using System;using System.Collections.Generic;using System.Text;using System.Text.RegularExpressions;using System.IO;using System.Threading;namespace ConsoleApplication1{class Program{static Thread th1;static Thread th2;static int value = 0;static void Main(string[] args){th1 = new Thread(new ThreadStart(Method1));th2 = new Thread(new ThreadStart(Method2));th1.Start();th2.Start();}static void Method1(){for (int i = 0; i < 1000000000; i++){value++;}Console.WriteLine("完成");}static void Method2(){while (true){ConsoleKeyInfo read = Console.ReadKey();if (char.IsLetter(read.KeyChar)){if (th1.ThreadState == ThreadState.Stopped){Console.WriteLine("th1已停止,按Esc键退出");continue;}th1.Suspend();Console.WriteLine("th1已挂起,value为{0}", value);}else if (read.Key == ConsoleKey.Spacebar){if (th1.ThreadState == ThreadState.Stopped){Console.WriteLine("th1已停止,按Esc键退出");continue;}else if (th1.ThreadState == ThreadState.Running){Console.WriteLine("th1正在运行");continue;}th1.Resume();Console.WriteLine("th1继续运行");}else if (read.Key == ConsoleKey.Escape){th1.Abort();th2.Abort();return;}}}}}
打开App,查看更多内容
随时随地看视频慕课网APP