我正在尝试模拟聊天客户端。首先是代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace thread
{
class Program
{
public static Thread t1;
public static Thread t2;
public static bool flag;
public static Random rand = new Random();
static void Main(string[] args)
{
t1 = new Thread(first);
t2 = new Thread(second);
t1.Start();
t2.Start();
Console.Read();
}
public static void first()
{
string[] phrase = { "Hello", "random", "blah,blah", "computer", "Welcome", "This is chat bot" };
while (!flag)
{
Thread.Sleep(4000);
Console.WriteLine("{0}", phrase[rand.Next(6)]);
}
}
public static void second()
{
string input = "";
while (input!="x")
{
input=Console.ReadLine();
if (input=="x")
{
break;
}
}
flag = true;
}
}
}
好的,所以这个程序会自动在控制台上打印一些文本,我也可以在屏幕上写我的信息。现在的问题是,每当我输入一个长句子时,任何需要超过 4 秒才能输入的内容。然后,它不会在下一行打印自动消息,而是附加到我正在输入的任何内容。我对多线程真的很陌生,所以我不确定是什么问题。我认为两个线程都使用相同的控制台类。
在这方面的帮助将不胜感激。