都知道singleton模式的线程安全方式有两种,一种是在GetInstance方法定义上加上synchronized的锁. 另一种方式是申明成static类型的变量.
我一直有一个疑问.net如何保证static类型是线程安全(实例化变量的操作时间很长,如何保证线程安全)? 我做了如下实验,的确是线程安全的.
[Form1.cs文件(对话框上仅一个按钮)]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ThreadStart(ShowBaseSalary));
Thread thread2 = new Thread(new ThreadStart(ShowBonusAndSalary));
thread1.Start();
thread2.Start();
}
private void ShowBaseSalary()
{
MessageBox.Show(Test.GetBaseSalary());
}
private void ShowBonusAndSalary()
{
MessageBox.Show(Test.GetBonusAndSalary(500));
}
}
class Test
{
private static Employee employee = new Employee(29); //实例化变量的时间可能很长,如何保证线程安全(线程1实例过程中,线程1有可能执行到该代码吗?)??
private int m = 0;
public static string GetBaseSalary()
{
return employee.GetBaseSalary();
}
public static string GetBonusAndSalary(int nBonus)
{
return employee.GetBonusAndSalary(nBonus);
}
}
</