您的位置:首页 > 其它

线程 线程池 线程同步 实例

2014-07-31 13:23 211 查看
线程:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace 线程Thread
{
class Program
{
public class MyThread
{
private string data;
public MyThread(string data)
{
this.data = data;
}
public void ThreadMain()
{
Console.WriteLine("Running in a thread,data :{0}", data);
}
}

static void Main(string[] args)
{
/*
* 第一种方法
//ThreadStart委托定义了一个返回类型为void 的无参数方法.在创建了Thread对象后,就可以使用start()方法启动线程
var t1 = new Thread(ThreadMain);
t1.Start();
Console.WriteLine("This is the main thread!");
*/
/*
//第二种方法
var t1 = new Thread(() =>
Console.WriteLine("running in a thread ,id :{0}", Thread.CurrentThread.ManagedThreadId));
t1.Start();
Console.WriteLine("This is the main thread ,id :{0}", Thread.CurrentThread.ManagedThreadId);
*/

//给线程传递数据 方法1
/*
var d = new Data { Message = "Info" };
var t2 = new Thread(ThreadMainWithParameters);

t2.Start(d);
*/
//给线程传递数据 方法2
/*
var obj = new MyThread("info");
var t3 = new Thread(obj.ThreadMain);
t3.Start();
*/

//后台线程 测试后台线程请去掉 Console.Read();
var t1 = new Thread(ThreadMain) { Name = "MyNewThreaad", IsBackground = true };
t1.Start();
Console.WriteLine("Main thread ending now.");

// Console.Read();
}
public struct Data
{
public string Message;
}
static void ThreadMainWithParameters(object o)
{
Data d = (Data)o;
Console.WriteLine("Running in a thread,received {0}", d.Message);
}

static void ThreadMain()
{
Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name);
Thread.Sleep(3000);
Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name);
//Console.WriteLine("Running in a thread.");
}
}
}


线程池:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace 线程池
{
class Program
{
static void Main(string[] args)
{
/*
1、线程池中所有线程都是后台线程,且不能更改
2、不能给入池的线程设置优先级或名称
3、对于COM对象 入池的线程都是多线程单元 (multithreaded apartment ,MTA)线程
* 许多COM对象需要单线程单元(single-threaded apartment,STA)线程
4、入池的线程只能用于较短的任务
*/

int nWorkerThreads;
int nCompletionPortThreads;
ThreadPool.GetMaxThreads(out nWorkerThreads, out nCompletionPortThreads);
Console.WriteLine("Max worker thread:{0} ," +
"I/O completion threads:{1}",
nWorkerThreads, nCompletionPortThreads);
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(JobForAThread);
}
Console.Read();
}
static void JobForAThread(object state)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("loop {0} ,running inside pooled thread {1} ", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(50);
}
}
}
}


线程同步:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace 线程同步
{
class Program
{
//lock 语句是设置锁定和解除锁定的一种简单方式
//用lock语句定义的对象表示,要等待指定对象的锁定解除  只能传送引用类型  因为锁定值类型只是锁定了一个副本
public class SharedState
{
private int state = 0;
private object syncRoot = new object();

public int State
{
get
{
lock (syncRoot)
{
return state;
}
}
set
{
lock (syncRoot)
{
state = value;
}
}
}
}

public class Task
{
SharedState sharedstate;
public Task( SharedState sharedstate)
{
this.sharedstate = sharedstate;
}
public void DoTheTask()
{
for (int i = 0; i < 50000; i++)
{
lock (sharedstate)
{
sharedstate.State += 1;
}
}
}
}

static void Main1(string[] args)
{
int numThreads = 20;
SharedState sharedState = new SharedState();
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new Thread(new Task(sharedState).DoTheTask);
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
Console.WriteLine("summarized {0} ", sharedState.State);
Console.Read();
}
}
}


线程同步:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace 线程同步
{
class tbInterlocked
{
//Interlocked 类用于使变量的简单语句原子化
/*
* Increment()  方法递增一个变量,把结果存储到一个原子操作中
* Decrement()  方法递减一个变量,并存储结果
* Exchange()   Exchange()将一个变量设置为指定的值,并返回变量的初始值
* CompareExchange()    对两个变量进行相等比较,如果他们相等,就设置指定的值,返回初始值
* Add()        Add()对 两个值进行相加操纵
* Read()       用于在一个原子操作中从内存读取64位值。在32为操作系统中,读取64位不是原子化的,而需要从两个内存地址中读取
*/
public class SharedState
{
private int state = 0;
public int State
{
get
{
return Interlocked.Increment(ref state);
}
}

private int decrement = 0;
/// <summary>
/// 这里是Decrment的实例
/// </summary>
public int Decrement
{
get
{
Console.WriteLine("decrement 的初始值为 {0}", decrement);
Interlocked.Decrement(ref decrement);
Console.WriteLine("调用interlocked.Decrement后的结果为{0}", decrement);
return decrement;
}

}
private int exchange = 0;
/// <summary>
///  这里是Exchange的实例
/// </summary>
public int Exchange
{
get
{
Console.WriteLine("exchange 的初始值为 {0}", exchange);
Interlocked.Exchange(ref exchange, 10);
Console.WriteLine("调用interlocked.Exchange后的结果为{0}", exchange);
return exchange;
}
}
}
public class Task
{
SharedState sharedstate;
public Task(SharedState sharedstate)
{
this.sharedstate = sharedstate;
}
public void ToTheTask()
{
for (int i = 0; i < 50000; i++)
{

int j= sharedstate.State;
}
}
}

static void Main2()
{
int numThreads = 20;
SharedState state = new SharedState();
Thread[] threads = new Thread[numThreads];

for (int i = 0; i < numThreads; i++)
{
threads[i] = new Thread(new Task(state).ToTheTask);
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
Console.WriteLine("结果 summarized {0}", state.State - 1);
Console.WriteLine("结果 +1 summarized {0}", state.State);
Console.WriteLine("调用2次后结果summarized {0}", state.State);

int iTest= state.Decrement;
iTest = state.Exchange;
Console.Read();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: