栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

C#用Monitor实现类似于Java的wait(), notify()

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#用Monitor实现类似于Java的wait(), notify()

有两个线程,一个线程输出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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322210.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号