using System;
using System.Threading;
using System.Collections;
//自己的线程包装器
interface IBookCollection
{
void Clear();
void Add(Book n);
Book GetBook(string ISBN);
bool IsSync{get;}
object Syncroot{get;}
}
class Book
{
public string Name;
public string ISBN;
public string Author;
public string Publisher;
}
class BookLib:IBookCollection
{
internal Hashtable bk=new Hashtable(10);
public virtual void Clear()
{
this.bk.Clear();
}
public virtual void Add(Book b)
{
Console.Write("Adding Book for ThreadID:"+
Thread.CurrentThread.GetHashCode());
Thread.Sleep(1000);
this.bk.Add(b.ISBN,b);
}
public virtual Book GetBook(string ISBN)
{
Console.Write("Getting Book for ThreadID:"+
Thread.CurrentThread.GetHashCode());
return (Book)bk[ISBN];
}
public virtual bool IsSync
{
get
{
return false;
}
}
public virtual object Syncroot
{
get
{
return this;
}
}
public BookLib Sync()
{
return Sync(this);
}
public static BookLib Sync(BookLib bc)
{
if(bc==null)
{
throw new ArgumentNullException("bc");
}
if(bc.GetType()==typeof(SyncBookLib))
{
throw new InvalidOperationException
("BookLib reference is already Sync.");
}
return new SyncBookLib(bc);
}
public static IBookCollection Sync(IBookCollection acc)
{
if(acc==null)
{
throw new ArgumentNullException("acc");
}
if(acc.GetType()==typeof(SyncBookLib))
{
throw new InvalidOperationException
(
"BookLib refernce is already sync."
);
}
return new SyncBookLib(acc);
}
}
sealed class SyncBookLib:BookLib
{
private object SyncRoot;
private object bookLib;
internal SyncBookLib(IBookCollection acc)
{
bookLib=acc;
SyncRoot=acc.Syncroot;
}
public override void Clear()
{
lock(SyncRoot)
{
base.Clear();
}
}
public override void Add(Book b)
{
lock(SyncRoot)
{
base.Add(b);
}
}
public override Book GetBook(string ISBN)
{
lock(SyncRoot)
{
return (Book)bk[ISBN];
}
}
public override bool IsSync
{
get
{
return false;
}
}
public override object Syncroot
{
get
{
return SyncRoot;
}
}
}
class Test
{
private static BookLib acc;
private static int n=0;
[STAThread]
static void Main(string[] args)
{
IBookCollection accInstanse=new BookLib();
string temp=null;
Console.WriteLine("请输入你是要同步还是不同步 Y/N");
temp=Console.ReadLine();
if(temp.ToLower()!="n")
{
acc=new SyncBookLib(accInstanse);
}
else
{
acc=new BookLib();
}
Thread[] threads={
new Thread(Run),new Thread(Run),new Thread(Run)
};
foreach(Thread t in threads)
{
t.Start();
}
foreach(Thread t in threads)
{
t.Join();
}
for (int i=0;i<n ;i++ ) {
Book bk=acc.GetBook(i.ToString());
if(bk!=null)
{
Console.WriteLine("Book:"+bk.Name);
Console.WriteLine("ISBN:"+bk.ISBN);
Console.WriteLine("Publisher:"+bk.Publisher);
Console.WriteLine("Author:"+bk.Author);
}
}
Console.WriteLine("Totao Number of Books Added "+n);
Console.Read();
}
static void Run()
{
for ( int i=0;i<2 ; i++) {
Book bk=new Book();
bk.Author="作者:小黎";
bk.Name="C#"+i;
bk.Publisher="人民出版社";
bk.ISBN=(n++).ToString();
acc.Add(bk);
}
}
}