using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication6_线程同步
{
public partial class Form1 : Form
{
//Forms.Control.CheckForIllegalCrossThreadCalls = false;
public Int64 number;
Thread thread1;
Thread thread2;
public bool fSync = false;
public common oCommon;
AddNumberClass addclass;
ReadNumber readclass;
public Form1()
{
InitializeComponent();
oCommon = new common();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
addclass = new AddNumberClass(this);
addclass.oCommon = oCommon;
thread1 = new Thread(new ThreadStart(addclass.Add));
thread1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
readclass = new ReadNumber(this);
readclass.oCommon = oCommon;
thread2 = new Thread(new ThreadStart(readclass.Read));
thread2.Start();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
fSync = !fSync;
}
}
public class common
{
}
public class AddNumberClass
{
public common oCommon;
Form1 oform;
public AddNumberClass(Form1 form)
{
oform = form;
}
// The nethod that will be called when the thread is started
public void Add()
{
int cLoop = 10;
//Obtain the lock
if (oform.fSync)
{
Monitor.Enter(oCommon);
}
while ((cLoop--) > 0)
{
oform.number++;
Int64 n = oform.number;
oform.textBox1.Text = n.ToString();
if (oform.fSync)
{
//Signal for next thread in wait queue to proceed
Monitor.Pulse(oCommon);
}
Thread.Sleep(100);
if (oform.fSync)
{
//Realease the lock and wait to be Notified
Monitor.Wait(oCommon);
}
//Realease the lock
if (oform.fSync)
{
Monitor.Exit(oCommon);
}
}
}
}
public class ReadNumber
{
public common oCommon;
Form1 oform;
public ReadNumber(Form1 form)
{
oform = form;
}
public void Read()
{
int cLoop = 10;
if (oform.fSync)
{
Monitor.Enter(oCommon);
}
while((cLoop--)>0)
{
Int64 n=oform.number;
oform.textBox2.Text=n.ToString();
if(oform.fSync)
{
//Signal for next thred in wait queue to proceed
Monitor.Pulse(oCommon);
}
Thread.Sleep(100);
if(oform.fSync)
{
//Realease the lock and wait to be Notified
Monitor.Wait(oCommon);
}
if(oform.fSync)
{
//Realease the lock
Monitor.Exit(oCommon);
}
}
}
}
}