有两个线程,一个线程输出A-Z,另一个线程输出1-52,现在要求两个线程交替输出,输出结果为A12B34C56…
Java实现
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Printer p = new Printer();
new Thread(() -> {
p.printA();
}).start();
new Thread(() -> {
p.printN();
}).start();
}
}
class Printer {
public synchronized void printN() {
int i = 1;
while (i <= 52) {
System.out.print(i);
i++;
System.out.print(i);
i++;
notify();
try {
wait();
} catch (Exception e) {
}
}
}
public synchronized void printA() {
char i = 'A';
while (i <= 'Z') {
System.out.print(i);
i++;
notify();
try {
wait();
} catch (Exception e) {
}
}
}
}
C#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
Printer p = new Printer();
Task.Factory.StartNew(() => { p.PrintA(); });
Task.Factory.StartNew(() => { p.PrintN(); });
Console.ReadLine();
}
}
class Printer
{
public object obj = new object();
public void PrintN()
{
int i = 1;
Monitor.Enter(obj);
while (i <= 52)
{
Console.Write(i);
i++;
Console.Write(i);
i++;
Monitor.Pulse(obj);
Monitor.Wait(obj);
}
Monitor.Exit(obj);
}
public void PrintA()
{
char a = 'A';
Monitor.Enter(obj);
while (a <= 'Z')
{
Console.Write(a);
a++;
Monitor.Pulse(obj);
Monitor.Wait(obj);
}
Monitor.Exit(obj);
}
}
}
输出结果均为:A12B34C56D78E910F1112G1314H1516I1718J1920K2122L2324M2526N2728O2930P3132Q3334R3536S3738T3940U4142V4344W4546X4748Y4950Z5152
|