单例模式,加锁 - 实践

单例模式

namespace 单例模式
{
internal class DanLi
{
int num = 100;
static DanLi d1=null;
int v;
private DanLi() { }
public static DanLi Create()
{
if (d1==null )
{
d1 = new DanLi();
}
return d1 ;
}
public  int M() { return --num; }
public  int k() { return ++num; }
}
namespace 单例模式
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Class1 c1=new Class1();
//textBox1.Text=c1.jai();
DanLi d = DanLi.Create();
textBox1.Text = d.M().ToString();
}
private void button2_Click(object sender, EventArgs e)
{
//Class2 c2 = new Class2();
//textBox1.Text = c2.jian();
DanLi d = DanLi.Create();
textBox1.Text=d.M().ToString();
}
}

加锁

namespace _4.线程同步Lock
{
internal class Danli
{
// 按照上节课 单例模式来说 在单线程上使用是完全没有没有问题的
// 但是在多线程的情况下 会出现多个Danli的实例  因为在多个线程同时运行时
// 调用GetDanli方法 此时两个线程执行判断时(dl==null) 这和条件有可能都返回真 就会创建两个danli 这样就违背了单例模式
//对于上面这种情况 我们可以使用lock  同一时间只执行一个
private static Danli dl;
private Danli() { }
//多线程场景
//定一个表示符  确保线程同步
private static readonly object locker = new object();
//设置一个供外部访问的全局点
public static Danli GetDl
{
get
{
//当第一个线程运行到这里是 此会对locker对象进行加锁
// 当第二个线程运行此方法时 lock首先会检测locker的"加锁"状态 该县就会被挂起等待
//等待到lock语句运行完毕解锁
lock (locker)
{
if (dl == null)
{
dl = new Danli();
}
return dl;
}
}
}
//双重锁定
public static Danli GetDl1()
{
if (dl ==null)
{
lock(locker)
{
if (dl ==null)
{
dl =new Danli();
}
}
}
return dl;
}
int i = 0;
public int _i
{
get
{
return i;
}
set
{
i = value;
}
}
}
class Test1
{
public void Get()
{
Danli d1 = Danli.GetDl;
d1._i = 100;
Console.WriteLine("这是T1访问dl的i值" + d1._i);
}
}
class Test2
{
public void Get()
{
Danli d2 = Danli.GetDl;
Console.WriteLine("这是T2访问Dl的i值" + d2._i);
}
}
}
namespace _4.线程同步Lock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread T1;
Thread T2;
private void Form1_Load(object sender, EventArgs e)
{
//多线程场景
T1 = new Thread(() =>
{
Test1 t1 = new Test1();
t1.Get();
});
T1.IsBackground = true;
T2 = new Thread(() =>
{
Test2 t2 = new Test2();
t2.Get();
});
T2.IsBackground = true;
T1.Start();
T2.Start();
}
}
}

posted @ 2025-09-17 11:23  yjbjingcha  阅读(7)  评论(0)    收藏  举报