P
pokémon
OK, if you run this code below (Console app) you will find that threads will
not always behave in a synchronized fashion, even with a lock
statement, --unless you put a Sleep somewhere in the method passed to
ThreadStart.
Try it, and please prove me wrong.
********
using System;
using System.Threading;
namespace TestLockPrivate
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
innerClass2 a = new innerClass2();
a.startme();
innerClass2 b = new innerClass2();
b.startme();
innerClass2 c = new innerClass2();
c.startme();
}
public class innerClass1 {
private object alock = new object();
private static string str = "";
public void foo() {
lock(alock) {
str = Thread.CurrentThread.GetHashCode().ToString();
if (str !=
Thread.CurrentThread.GetHashCode().ToString()) {
Console.WriteLine("str = " + str + "
Thread.CurrentThread.GetHashCode().ToString() = " +
Thread.CurrentThread.GetHashCode().ToString());
}
}
}
}
public class innerClass2 {
public Thread t = null;
public void startme() {
t = new Thread(new ThreadStart(threadMain));
t.Start();
}
public void threadMain() {
while (true) {
innerClass1 l = new innerClass1();
l.foo();
}
}
}
}
}
not always behave in a synchronized fashion, even with a lock
statement, --unless you put a Sleep somewhere in the method passed to
ThreadStart.
Try it, and please prove me wrong.
********
using System;
using System.Threading;
namespace TestLockPrivate
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
innerClass2 a = new innerClass2();
a.startme();
innerClass2 b = new innerClass2();
b.startme();
innerClass2 c = new innerClass2();
c.startme();
}
public class innerClass1 {
private object alock = new object();
private static string str = "";
public void foo() {
lock(alock) {
str = Thread.CurrentThread.GetHashCode().ToString();
if (str !=
Thread.CurrentThread.GetHashCode().ToString()) {
Console.WriteLine("str = " + str + "
Thread.CurrentThread.GetHashCode().ToString() = " +
Thread.CurrentThread.GetHashCode().ToString());
}
}
}
}
public class innerClass2 {
public Thread t = null;
public void startme() {
t = new Thread(new ThreadStart(threadMain));
t.Start();
}
public void threadMain() {
while (true) {
innerClass1 l = new innerClass1();
l.foo();
}
}
}
}
}