当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET:一段比较经典的多线程学习代码

ASP.NET
asp.net GridView控件中模板列CheckBox全选、反选、取消
asp.net GridView 删除时弹出确认对话框(包括内容提示)
asp.net DropDownList 三级联动下拉菜单实现代码
asp DataTable添加列和行的三种方法
Asp.net 页面调用javascript变量的值
asp.net 长文章通过设定的行数分页
asp.net 定时间点执行任务的简易解决办法
asp.net 页面延时五秒,跳转到另外的页面
asp.net 动态输出透明gif图片
asp.net DataList与Repeater用法区别
asp.net Javascript获取CheckBoxList的value
asp.net程序在调式和发布之间图片路径问题的解决方法
asp.net下生成英文字符数字验证码的代码
asp.net 页面版文本框智能提示JSCode (升级版)
ASP.NET URL伪静态重写实现方法
ASP.NET 2.0 中Forms安全认证
asp.net 动态添加多个用户控件
asp.net Repeater显示父子表数据,无闪烁
asp.net 无法获取的内部内容,因为该内容不是文本 的解决方法
asp.net GridView排序简单实现

ASP.NET:一段比较经典的多线程学习代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 114 ::
收藏到网摘: n/a

  一段比较经典的多线程学习代码。

  1、用到了多线程的同步问题。
  2、用到了多线程的顺序问题。

  如果有兴趣的请仔细阅读下面的代码。注意其中代码段的顺序,思考一下,这些代码的顺序能否互相调换,为什么?这应该对学习很有帮助的。为了演示,让所有的线程都Sleep了一段时间。

using System.Net;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Webb.Study
{
class TestThread
{
static Mutex m_Mutex = new Mutex();
static Thread[] m_testThreads = new Thread[10];
static int m_threadIndex = 0;

static void ThreadCallBack()
{
TestThread.m_Mutex.WaitOne();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex();
Console.WriteLine("Thread {0} start.",m_index);
for(int i=0;i<=10;i++)
{
TestThread.m_Mutex.WaitOne();
Console.WriteLine("Thread {0}: is running. {1}",m_index,i);
TestThread.m_Mutex.ReleaseMutex();
Thread.Sleep(100);
}
Console.WriteLine("Thread {0} end.",m_index);
}

public static void Main(String[] args)
{
Console.WriteLine("Main thread start.");
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_threadIndex = i;
TestThread.m_testThreads[i] = new Thread(new ThreadStart(ThreadCallBack));
TestThread.m_testThreads[i].Start();
Thread.Sleep(100);
}
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_testThreads[i].Join();
}
Console.WriteLine("Main thread exit.");
}
}
}

  1、主函数中这两句能否互换?为什么?

TestThread.m_testThreads[i].Start();
Thread.Sleep(100);

  2、CallBack函数中这两句能否互换?为什么?会有什么不同的结果?

TestThread.m_Mutex.ReleaseMutex();
Thread.Sleep(100);

  3、主函数能否写成这样?为什么?会有什么不同的结果?

public static void Main(String[] args)
{
Console.WriteLine("Main thread start.");
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_threadIndex = i;
TestThread.m_testThreads[i] = new Thread(new ThreadStart(ThreadCallBack));
TestThread.m_testThreads[i].Start();
TestThread.m_testThreads[i].Join();
Thread.Sleep(100);
}
Console.WriteLine("Main thread exit.");
}

  4、这几句的作用是什么?那么程序中还存在什么样的问题?应该做怎样的修改?

TestThread.m_Mutex.WaitOne();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex();

仅做学习讨论。