C# 实现java中 wiat/notify机制

时间:2023-03-09 09:55:48
C# 实现java中 wiat/notify机制

最近在学习java,看到wiat/notify机制实现线程通信,由于平时工作用的C#,赶紧用C#方式实现一个demo。

Java 代码:

import java.util.ArrayList;
import java.util.List; public class MyList { private static List list = new ArrayList(); public static void add() {
list.add("anyString");
} public static int size() {
return list.size();
} } import extlist.MyList; public class ThreadA extends Thread { private Object lock; public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
synchronized (lock) {
if (MyList.size() != ) {
System.out.println("wait begin "
+ System.currentTimeMillis());
lock.wait();
System.out.println("wait end "
+ System.currentTimeMillis());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} } import extlist.MyList; public class ThreadB extends Thread {
private Object lock; public ThreadB(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
synchronized (lock) {
for (int i = ; i < ; i++) {
MyList.add();
if (MyList.size() == ) {
lock.notify();
System.out.println("已发出通知!");
}
System.out.println("添加了" + (i + ) + "个元素!");
Thread.sleep();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} } import extthread.ThreadA;
import extthread.ThreadB; public class Run { public static void main(String[] args) { try {
Object lock = new Object(); ThreadA a = new ThreadA(lock);
a.start(); Thread.sleep(); ThreadB b = new ThreadB(lock);
b.start();
} catch (InterruptedException e) {
e.printStackTrace();
} } }

C# 实现java中 wiat/notify机制

C# 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading; namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var obj = new object();
var thread1 = new Thread(Test1);
thread1.Start(obj); Thread.Sleep(); var thread2 = new Thread(Test2);
thread2.Start(obj);
} public static void Test1(object obj)
{
try
{
Monitor.Enter(obj);
if (MyList.Size() != )
{
Console.WriteLine("wait begin" + DateTime.Now);
Monitor.Wait(obj);
Console.WriteLine("wait end" + DateTime.Now);
}
Monitor.Exit(obj);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} public static void Test2(object obj)
{
try
{
Monitor.Enter(obj);
for (int i = ; i < ; i++)
{
MyList.Add();
if (MyList.Size() == )
{
Monitor.Pulse(obj);
Console.WriteLine("已发出通知!" + DateTime.Now);
}
Console.WriteLine("添加了(" + (i + ) + ")个元素");
Thread.Sleep();
}
Monitor.Exit(obj);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
} public class MyList
{
private static readonly List<string> list = new List<string>(); public static void Add()
{
list.Add("anyString");
} public static int Size()
{
return list.Count();
}
}
}

C# 实现java中 wiat/notify机制