Thread security issues are generated when multiple threads accesses the shared area. For example: using system; using system.threading;
Class Account {Int Balance;
Random r = new random ();
Public Account (int initial) {balance = initial;
INT withDRAW (int Amount) {
IF (Balance <0) {Throw new Exception ("Negative Balance");
// Comment Out the next line to see the effect of leaving out // The Lock Keyword:
IF (Balance> = Amount) {Console.Writeline ("Amount to with DRITELINE (" Amount to Withdraw: - " Amount); Balance = Balance - Amount; Console.Writeline (" BalanceAfter WITHDRAWAL: " Balance); Return Amount;} else {return 0;}
}
Public void dotransactions () {for (int i = 0; i <100; i ) {withdraw (R.Next (1, 100));}}}
Class test {public static void main () {thread [] threads = new thread [10]; // 10 thread access sharing area Account ACC = New Account (1000); for (INT i = 0; i <10; i ) ) {Thread T = New Thread (ACC.DOTRANSACTION); threads [i] = t;} for (int i = 0; i <10; i ) {threads [i] .start ();}} } The program is changed to, you can: using system; using system.threading;
Class Account {Int Balance;
Random r = new random ();
Public Account (int initial) {balance = initial;
INT withDRAW (int Amount) {
// this condition will never be true unless the lock statement // is commented out: IF (Balance <0) {throw new exception ("negative balance");}
// Comment Out the next line to see the effect of leaving out // The Lock Keyword: Lock (this) {if (Balance> = Amount) {Console.Writeline ("Balance Before withdrawal: balance); console.writeline ("Amount to Withdraw: -" Amount); Balance = Balance - Amount; Console.Writeline ("Balance After Withdrawal: Balance); Return Amount;} else {return 0; // Transaction rejected}}} public void Dotransactions () {for (int i = 0; i <100; i ) {withdraw (R.Next (1, 100));}}}
Class test {public static void () {thread [] threads = new thread [10]; Account ACC = New Account (1000); for (int i = 0; i <10; i ) {thread T = New Thread New threadstart (acc.dotransactions); threads [i] = t;} for (int i = 0; i <10; i ) {threads [i] .start ();}}} This is like version control principle. LOCK can also solve multi-threaded unsafe issues in Singleton. Here, a lazy mode of Singleton thread security code: public sealed class singletontest {private singletontest () {// Todo: Some initialization} // m_instance This is applauded to volatile, and it can be accessed when the variable is completed. private static volatile SingletonTest m_instance = null; private static Object sync = new Object (); public static SingletonTest createInstance () {if (m_instance == null) {lock (sync) {m_instance = new SingletonTest ();}} return m_instance; }