标签:
class Program{static void Main(string[] args){for (int i = 0; i < 30; i++){ThreadStart threadStart = new ThreadStart(Calculate);Thread thread = new Thread(threadStart);thread.Start();}Thread.Sleep(2000);Console.Read();}public static void Calculate(){DateTime time = DateTime.Now;//得到当前时间Random ra = new Random();//随机数对象Thread.Sleep(ra.Next(10,100));//随机休眠一段时间Console.WriteLine(time.Minute + ":" + time.Millisecond);}}
class Program{static void Main(string[] args){for (int i = 0; i < 30; i++){ParameterizedThreadStart tStart = new ParameterizedThreadStart(Calculate);Thread thread = new Thread(tStart);thread.Start(i*10+10);//传递参数}Thread.Sleep(2000);Console.Read();}public static void Calculate(object arg){Random ra = new Random();//随机数对象Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间Console.WriteLine(arg);}}
class Program{static void Main(string[] args){MyThread mt = new MyThread(100);ThreadStart threadStart = new ThreadStart(mt.Calculate);Thread thread = new Thread(threadStart);thread.Start();//等待线程结束while (thread.ThreadState != ThreadState.Stopped){Thread.Sleep(10);}Console.WriteLine(mt.Result);//打印返回值Console.Read();}}public class MyThread//线程类{public int Parame { set; get; }//参数public int Result { set; get; }//返回值//构造函数public MyThread(int parame){this.Parame = parame;}//线程执行方法public void Calculate(){Random ra = new Random();//随机数对象Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间Console.WriteLine(this.Parame);this.Result = this.Parame * ra.Next(10, 100);}}
class Program{static void Main(string[] args){int Parame = 100;//当做参数int Result = 0;//当做返回值//匿名方法ThreadStart threadStart = new ThreadStart(delegate(){Random ra = new Random();//随机数对象Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间Console.WriteLine(Parame);//输出参数Result = Parame * ra.Next(10, 100);//计算返回值});Thread thread = new Thread(threadStart);thread.Start();//多线程启动匿名方法//等待线程结束while (thread.ThreadState != ThreadState.Stopped){Thread.Sleep(10);}Console.WriteLine(Result);//打印返回值Console.Read();}}
class Program{private delegate int NewTaskDelegate(int ms);private static int newTask(int ms){Console.WriteLine("任务开始");Thread.Sleep(ms);Random random = new Random();int n = random.Next(10000);Console.WriteLine("任务完成");return n;}static void Main(string[] args){NewTaskDelegate task = newTask;IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);//EndInvoke方法将被阻塞2秒int result = task.EndInvoke(asyncResult);Console.WriteLine(result);Console.Read();}}
class Program{private delegate int NewTaskDelegate(int ms);private static int newTask(int ms){Console.WriteLine("任务开始");Thread.Sleep(ms);Random random = new Random();int n = random.Next(10000);Console.WriteLine("任务完成");return n;}static void Main(string[] args){NewTaskDelegate task = newTask;IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);//等待异步执行完成while (!asyncResult.IsCompleted){Console.Write("*");Thread.Sleep(100);}// 由于异步调用已经完成,因此, EndInvoke会立刻返回结果int result = task.EndInvoke(asyncResult);Console.WriteLine(result);Console.Read();}}
class Program{private delegate int NewTaskDelegate(int ms);private static int newTask(int ms){Console.WriteLine("任务开始");Thread.Sleep(ms);Random random = new Random();int n = random.Next(10000);Console.WriteLine("任务完成");return n;}static void Main(string[] args){NewTaskDelegate task = newTask;IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);//等待异步执行完成while (!asyncResult.AsyncWaitHandle.WaitOne(100, false)){Console.Write("*");}int result = task.EndInvoke(asyncResult);Console.WriteLine(result);Console.Read();}}
class Program{private delegate int MyMethod(int second, int millisecond);//线程执行方法private static int method(int second, int millisecond){Console.WriteLine("线程休眠" + (second * 1000 + millisecond) + "毫秒");Thread.Sleep(second * 1000 + millisecond);Random random = new Random();return random.Next(10000);}//回调方法private static void MethodCompleted(IAsyncResult asyncResult){if (asyncResult == null || asyncResult.AsyncState == null){Console.WriteLine("回调失败!!!");return;}int result = (asyncResult.AsyncState as MyMethod).EndInvoke(asyncResult);Console.WriteLine("任务完成,结果:" + result);}static void Main(string[] args){MyMethod my = method;IAsyncResult asyncResult = my.BeginInvoke(3,300, MethodCompleted, my);Console.WriteLine("任务开始");Console.Read();}}
class Program{//回调函数private static void requestCompleted(IAsyncResult asyncResult){if (asyncResult == null || asyncResult.AsyncState==null){Console.WriteLine("回调失败");return;}HttpWebRequest hwr = asyncResult.AsyncState as HttpWebRequest;HttpWebResponse response = (HttpWebResponse)hwr.EndGetResponse(asyncResult);StreamReader sr = new StreamReader(response.GetResponseStream());string str = sr.ReadToEnd();Console.WriteLine("返回流长度:"+str.Length);}static void Main(string[] args){HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");//异步请求IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);Console.WriteLine("任务开始");Console.Read();}}



//按钮事件private void button1_Click(object sender, EventArgs e){Thread thread = new Thread(Flush);thread.IsBackground = true;//设置成后台线程thread.Start();}//线程执行的方法private void Flush(){//定义委托Action action = delegate(){this.textBox1.AppendText(DateTime.Now.ToString() + "\r\n");};while (true){//判断能否到当前线程操作该组件if (this.textBox1.InvokeRequired){//不在当前线程上操作this.textBox1.Invoke(action);//调用委托}else{//在当前线程上操作this.textBox1.AppendText(DateTime.Now.ToString() + "\r\n");}Thread.Sleep(1000);}}
//按钮事件private void button1_Click(object sender, EventArgs e){this.backgroundWorker1.RunWorkerAsync();//处理事务}//处理事务事件private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){//初始化进度条this.progressBar1.Maximum = 100;this.progressBar1.Minimum = 0;//模拟事物处理for (int i = 0; i < 100; i++){Thread.Sleep(10);//局部操作完成事件触发this.backgroundWorker1.ReportProgress(i, null);}}//局部操作完成时执行的方法private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){this.progressBar1.Value = e.ProgressPercentage;//设置进度条值}//事物处理完成时触发private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e){MessageBox.Show(null, "工作线程完成!", "提示");}
class Program{//线程方法public static void ThreadProc(object i){Console.WriteLine(i.ToString());Thread.Sleep(1000);}public static void Main(){ThreadPool.SetMaxThreads(3, 3);//设置线程池for (int i = 0; i < 10; i++){ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), "线程" + i);}Console.WriteLine("运行结束");Console.Read();}}
class Program{private int Count = 0;//线程执行方法public void ThreadProc(){Monitor.Enter(this);Thread.Sleep(200);Count++;Console.WriteLine(Count);Monitor.Exit(this);//等同于//lock (this)//{// Thread.Sleep(200);// Count++;// Console.WriteLine(Count);//}}public static void Main(){Program p = new Program();for (int i = 0; i < 100; i++){Thread t = new Thread(p.ThreadProc);t.Start();}Console.Read();}}
class Program{private static Mutex mutex;static void Main(string[] args){mutex = new Mutex(false);for (int i = 0; i < 10; i++){Thread thread = new Thread(Method);thread.Start("线程" + i);}Console.WriteLine("主线程执行完毕");Console.ReadLine();}//线程执行方法private static void Method(Object o){mutex.WaitOne();//等待信号for (int i = 0; i < 3; i++){Thread.Sleep(500);Console.WriteLine(o.ToString() + "循环" + i);}mutex.ReleaseMutex();//释放信号}}
class Program{static void Main(string[] args){bool flag = false;Mutex mutex = new Mutex(true, "Test", out flag);//第一个参数:true--给调用线程赋予互斥体的初始所属权//第一个参数:互斥体的名称//第三个参数:返回值,如果调用线程已被授予互斥体的初始所属权,则返回trueif (flag){Console.Write("进程运行...");}else{Console.Write("这个进程正在运行!");Thread.Sleep(5000);//线程挂起5秒钟Environment.Exit(1);//退出程序}Console.ReadLine();}}
class Program{public static void Main(){AutoResetEvent[] Waits = new AutoResetEvent[10];for (int i = 0; i < 10; i++){int temp = i;Waits[temp] = new AutoResetEvent(false);Action thread = delegate(){//线程执行方法Console.WriteLine("线程:" + temp);Thread.Sleep(1000);Waits[temp].Set();//发送线程执行完毕信号};ThreadStart ts = new ThreadStart(thread);Thread t = new Thread(ts);t.Start();}AutoResetEvent.WaitAll(Waits);//等待Waits中的所有对象发出信号Console.WriteLine("线程全部执行完毕!");Console.Read();}}
class Program{public static void Main(){AutoResetEvent[] Waits = new AutoResetEvent[10];for (int i = 0; i < 10; i++){Waits[i] = new AutoResetEvent(false);//初始化Waits}for (int i = 0; i < 10; i++){int temp = i;Action thread = delegate(){if (temp > 0){AutoResetEvent.WaitAny(Waits);//等待上一个线程执行完毕}//线程执行方法Thread.Sleep(1000);Waits[temp].Set();//发送线程执行完毕信号Console.WriteLine("线程:" + temp+"执行完毕");};ThreadStart ts = new ThreadStart(thread);Thread t = new Thread(ts);t.Start();}Console.Read();}}
class Program{public static void Main(){AutoResetEvent Wait = new AutoResetEvent(false);for (int i = 0; i < 10; i++){Action thread = delegate(){//线程执行方法Thread.Sleep(1000);Wait.Set();//发送线程执行完毕信号Console.WriteLine("线程:" + i+"执行完毕");};ThreadStart ts = new ThreadStart(thread);Thread t = new Thread(ts);t.Start();Wait.WaitOne();//等待调用 Waits.Set()}Console.Read();}}
class Program{private static ManualResetEvent Wait = new ManualResetEvent(false);public static void Main(){Wait.Set();//设置线程状态为允许执行Thread thread1 = new Thread(Method);thread1.Start("线程1");Thread.Sleep(1000);//等待线程1执行Wait.Reset();//必须手动复位线程状态,使状态为不允许执行Thread thread2 = new Thread(Method);thread2.Start("线程2");//线程2将会一直等待信号Console.WriteLine("主线程结束");Console.Read();}//线程执行方法private static void Method(Object o){Wait.WaitOne();//等待信号Console.WriteLine(o.ToString());}}
class Program{private static int Count = 0;static void Main(string[] args){for (int i = 0; i < 100; i++){Thread thread = new Thread(Method);thread.Start("线程" + i);}Thread.Sleep(1000 * 3);//休眠足够的时间等待所有线程执行完毕Console.WriteLine("操作后的结果:" + Program.Count);Console.ReadLine();}//线程执行方法private static void Method(Object o){Thread.Sleep(500);//原子操作,类似:Program.Count++Interlocked.Increment(ref Program.Count);//Program.Count++;//非原子操作Console.WriteLine(o.ToString());}}
class Program{private static int Count = 0;//资源static ReaderWriterLock rwl = new ReaderWriterLock();//读、写操作锁static void Main(string[] args){for (int i = 0; i < 10; i++){Thread thread = new Thread(Read);//读线程thread.Start("线程" + i);}for (int i = 0; i < 10; i++){Thread thread = new Thread(Write);//写线程thread.Start("--线程" + i);}Console.ReadKey();}private static void Read(Object o)//读数据{rwl.AcquireReaderLock(1000 * 20); //申请读操作锁,在20s内未获取读操作锁,则放弃Console.WriteLine(o.ToString() + "读取数据:" + Program.Count);Thread.Sleep(500);rwl.ReleaseReaderLock();//释放读操作锁}private static void Write(Object o)//写数据{rwl.AcquireWriterLock(1000 * 20);//申请写操作锁,在20s内未获取写操作锁,则放弃Thread.Sleep(500);Console.WriteLine(o.ToString() + "写数据:" + (++Program.Count));rwl.ReleaseWriterLock();//释放写操作锁}}
class Program{private static Semaphore semaphore = new Semaphore(0, 5);//初始化信号量static void Main(string[] args){for (int i = 0; i < 10; i++){Thread thread = new Thread(Method);thread.Start("线程" + i);}semaphore.Release(2);//释放信号量2个Console.WriteLine("主线程运行完毕!");Console.Read();}//线程执行方法private static void Method(object o){semaphore.WaitOne();//等待信号量Thread.Sleep(1000);Console.WriteLine(o.ToString());semaphore.Release();//释放信号量}}
class Program{static void Main(string[] args){//初始信号量5个,最多信号量10个Semaphore seamphore = new Semaphore(5, 10, "Test");seamphore.WaitOne();//等待信号Console.WriteLine("获取信号量 1");seamphore.WaitOne();//等待信号Console.WriteLine("获取信号量 2");seamphore.WaitOne();//等待信号Console.WriteLine("获取信号量 3");Console.WriteLine("主线程运行完毕!");Console.Read();}}

class Program{static void Main(string[] args){System.Timers.Timer t = new System.Timers.Timer(1000);//产生事件的时间间隔1st.Elapsed += new ElapsedEventHandler(Method); //到达时间的时候执行事件t.AutoReset = true;//设置是执行一次(false)还是一直执行(true)t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件Console.WriteLine("完成!");Console.Read();}private static void Method(object source,ElapsedEventArgs e){Console.WriteLine("时间:"+e.SignalTime);}}
标签:
原文地址:http://www.cnblogs.com/LiZhiW/p/4315510.html