写了个测试程序,主要是多线程情况下交换数组的两个成员,我这程序最后的结果出了问题,数组的元素和原来的不一样.请问哪出问题了?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace ConsoleApplication2
{
class Program
{ static int k = 0;
static int cou = 10000;
static int[] arr = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
static object obj = new object(); static void Main(string[] args)
{
Thread thread1 = new Thread(fun1);
Thread thread2 = new Thread(fun2);
Thread thread3 = new Thread(fun3);
Thread thread4 = new Thread(fun4);
Thread thread5 = new Thread(fun5); thread1.Start();
thread2.Start();
thread3.Start();
thread4.Start();
thread5.Start(); for (int i = 0; i < 10; i++)
{
Console.WriteLine(arr[i].ToString());
} Console.ReadLine();
}
static void test()
{
for (int i = 0; i < cou; i++)
{
Random ran = new Random();
int m = ran.Next(10); int n = ran.Next(10); while (m == n)
{
n = ran.Next(10); }
lock (obj)
{
int temp = arr[m];
arr[m] = arr[n];
arr[n] = temp;
}
}
} static void fun1()
{
test();
} static void fun2()
{
test();
}
static void fun3()
{
test();
}
static void fun4()
{
test();
}
static void fun5()
{
test();
} }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace ConsoleApplication2
{
class Program
{ static int k = 0;
static int cou = 10000;
static int[] arr = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
static object obj = new object(); static void Main(string[] args)
{
Thread thread1 = new Thread(fun1);
Thread thread2 = new Thread(fun2);
Thread thread3 = new Thread(fun3);
Thread thread4 = new Thread(fun4);
Thread thread5 = new Thread(fun5); thread1.Start();
thread2.Start();
thread3.Start();
thread4.Start();
thread5.Start(); for (int i = 0; i < 10; i++)
{
Console.WriteLine(arr[i].ToString());
} Console.ReadLine();
}
static void test()
{
for (int i = 0; i < cou; i++)
{
Random ran = new Random();
int m = ran.Next(10); int n = ran.Next(10); while (m == n)
{
n = ran.Next(10); }
lock (obj)
{
int temp = arr[m];
arr[m] = arr[n];
arr[n] = temp;
}
}
} static void fun1()
{
test();
} static void fun2()
{
test();
}
static void fun3()
{
test();
}
static void fun4()
{
test();
}
static void fun5()
{
test();
} }
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货