class Program
{
static object obj = new object();
static int i = 10000;
static double start;
static double end; static void Main(string[] args)
{
Thread th1 = new Thread(new ThreadStart(Count));
Thread th2 = new Thread(new ThreadStart(Count));
th1.Name = "线程1";
th2.Name = "线程2";
th1.Start();
th2.Start();
Console.Read();
} private static void Count()
{
start = Convert.ToInt32(DateTime.Now.ToString("ms"));
while (i > 0)
{
lock (obj)
{
if (i > 0)
{
i--;
Console.WriteLine(Thread.CurrentThread.Name + "减1等于" + i);
Console.WriteLine(end = start - Convert.ToInt32(DateTime.Now.ToString("ms")));
}
}
}
}
}2条线程同步倒数是5-6秒6条线程同步倒数还是5-6秒,,是不是代码哪里写错了?
{
static object obj = new object();
static int i = 10000;
static double start;
static double end; static void Main(string[] args)
{
Thread th1 = new Thread(new ThreadStart(Count));
Thread th2 = new Thread(new ThreadStart(Count));
th1.Name = "线程1";
th2.Name = "线程2";
th1.Start();
th2.Start();
Console.Read();
} private static void Count()
{
start = Convert.ToInt32(DateTime.Now.ToString("ms"));
while (i > 0)
{
lock (obj)
{
if (i > 0)
{
i--;
Console.WriteLine(Thread.CurrentThread.Name + "减1等于" + i);
Console.WriteLine(end = start - Convert.ToInt32(DateTime.Now.ToString("ms")));
}
}
}
}
}2条线程同步倒数是5-6秒6条线程同步倒数还是5-6秒,,是不是代码哪里写错了?
你写的东西首先并没有必要使用多线程,又没有任何等待或空闲的资源可以用多线程去发挥其优势。
再则你写的东西一个LOCK就没意义了,几个线程抢,最后跑还是一个个的来。你可以换个东西来实现,比如下载一批地址中的数据,这样就明显了
嗯,,明白了,我把Lock去掉了
而是lock只用在确实需要的地方