一、实验目的与要求
编写两个线程,一个线程打印1-52的整数,另一个线程打印字母A-Z。打印顺序为12A34B56C….5152Z。即按照整数和字母的顺序从小到大打印,并且每打印两个整数后,打印一个字母,交替循环打印,直到打印到整数52和字母Z结束。
要求:
1) 编写打印类Printer,声明私有属性index,初始值为1,用来表示是第几次打印。
2) 在打印类Printer中编写打印数字的方法print(int i),3的倍数就使用Sleep方法等待,否则就输出i,使用Interrupt进行唤醒其它线程。
3) 在打印类Printer中编写打印字母的方法print(char c),不是3的倍数就等待,否则就打印输出字母c,使用Interrupt进行唤醒其它线程。
4) 编写测试类Test,创建打印类对象,创建两个线程类对象,启动线程。
二、实验内容与步骤
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Multipleprocesses
{
public class Program
{
internal class Printer
{
private int index = 1;//用于统计第几次打印
public void print(int data)
{
while (index % 3 == 0)
{
try
{
Thread.Sleep(1000);
}
catch (Exception e)
{
if (e.ToString() != null) { } ;
}
}
Console.WriteLine("数字:"+ data);
index++;
ts.Interrupt();
}
//打印字母,每打印一个字母,等待打印两个数字
public void print(char c)
{
while (index % 3 != 0)
{
try
{
Thread.Sleep(900);
}
catch (Exception e)
{
if (e.ToString() != null) { };
}
}
Console.WriteLine("字母:" + c);
index++;
tz.Interrupt();
}
}
internal class NumberPrinter
{
private Printer p;
public NumberPrinter(Printer p)
{
this.p = p;
}
public void run()
{
for (int i = 1; i <= 52; i++)
{
p.print(i);
}
}
}
internal class LetterPrinter
{
private Printer p;
public LetterPrinter(Printer p)
{
this.p = p;
}
public void run()
{
for (char c = 'A'; c <= 'Z'; c++)
{
p.print(c);
}
}
}
private static Thread ts;
private static Thread tz;
static void Main(string[] args)
{
//测试类
Printer p = new Printer(); //创建打印机对象
NumberPrinter f = new NumberPrinter(p);
LetterPrinter g = new LetterPrinter(p);
Thread f2 = new Thread(f.run);
Thread g2 = new Thread(g.run);
ts = f2;
tz = g2;
f2.Start();
g2.Start();
Console.ReadKey();
}
}
}
运行截图: