运行结果:
源码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private object obj;
private void ceshiThread(Object obj)
{
Stopwatch sp = new Stopwatch();
sp.Restart();
int index = (int)obj;
int count = 0;
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
int value = i * j;
count++;
}
}
sp.Stop();
textBox1.AppendText(string.Format("线程 {0} 执行次数 {1} ,总耗时 {2}", index, count, sp.ElapsedMilliseconds.ToString()));
textBox1.AppendText(Environment.NewLine);
}
private void button1_Click(object sender, EventArgs e)
{
//int a = 0;
//while (a < 100)
{
for (int i = 0; i < 4; i++)
{
Thread th = new Thread(ceshiThread);
th.IsBackground = true;
th.Start(i);
//Task t = new Task(() => ceshiThread(i));
//t.Start();
}
//a++;
//Thread.Sleep(5);
}
}
private void button2_Click(object sender, EventArgs e)
{
//Parallel.For(0, 4, (i) =>
//{
// ceshiThread(i);
//});
for (int i = 0; i < 4; i++)
{
ThreadPool.QueueUserWorkItem(ceshiThread, i);
}
//Task t = new Task(() => ceshiThread(0));
//t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
//for (int i = 0; i < 100; i++)
//{
Thread th = new Thread(ceshiThread);
th.IsBackground = true;
th.Start(1);
//Thread.Sleep(200);
//}
//Thread th = new Thread(ceshiThread);
//th.IsBackground = true;
//th.Start(1);
}
}
}