你这是操作系统习题吧?
呵呵,最近正好了解线程方面的,贴第二题:(我测试了下。基本上所有数都会按顺序并且连续的输出。。你自己也测下。)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static bool IsContinue = true;
static int currentNum = -1;
static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(delegate()
{
do
{
Program.IncreaseNum();
}
while (IsContinue);
});
Thread writeThread1 = new Thread(ts);
Thread writeThread2 = new Thread(ts);
Thread writeThread3 = new Thread(ts);
ThreadStart readTs = new ThreadStart(delegate()
{
do
{
int num = Program.ReadNum();
if (currentNum != num)
{
Console.Write(num.ToString()+"\n");
currentNum = num;
}
}
while (IsContinue);
});
Thread readThread = new Thread(readTs);
readThread.Start();
writeThread1.Start();
writeThread2.Start();
writeThread3.Start();
//readThread.Start(
}
public static int Num = 0;
public static ReaderWriterLock RWL = new ReaderWriterLock();
public static void IncreaseNum()
{
RWL.AcquireWriterLock(Timeout.Infinite);
try
{
Num++;
Thread.Sleep(Num);
}
finally
{
RWL.ReleaseReaderLock();
}
}
public static int ReadNum()
{
RWL.AcquireReaderLock(Timeout.Infinite);
try
{
return Num;
}
finally
{
RWL.ReleaseReaderLock();
}
}
}
}
刚好以前写过一个测试通讯是正常的例子:
第一题:
服务端代码:
static void Main(string[] args)
{
System.Net.Sockets.TcpListener lister = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Parse("192.168.1.108"), 9643);
lister.Start();
System.Net.Sockets.NetworkStream stream = null;
byte[] data = new byte[256];
Write("正在等待链接...");
System.Net.Sockets.TcpClient server = lister.AcceptTcpClient();
bool connect = false;
while (true)
{
stream = server.GetStream();
int i;
try
{
while ((i = stream.Read(data, 0, data.Length)) != 0)
{
if (!connect)
{
connect = true;
Write("已建立链接...");
}
Write(System.Text.Encoding.Default.GetString(data));
}
}
catch
{
Write("已链接已关闭...");
}
}
}
public static void Write(string msg)
{
Console.WriteLine(msg.Trim());
}
}
客户端代码:
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("192.168.1.108"), 9643);
Byte[] data = null;
string msg = null;
NetworkStream stream = null;
while (true)
{
msg = Console.ReadLine();
if (msg != "bye")
{
data = System.Text.Encoding.ASCII.GetBytes(msg);
stream = client.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", msg);
}
else
{
stream = null;
client.Close();
break;
}
}
}