您的位置:首页 > 编程语言 > C#

通过线程计数器和Thread.Join方法得到线程已完成状态

2015-08-11 23:24 701 查看
方法一:线程计数器



class Program
{
static void Main(string[] args)
{
Thread[] ths = new Thread[3];

ThreadCounter counter1 = new ThreadCounter(1000);
ThreadCounter counter2 = new ThreadCounter(3000);
ThreadCounter counter3 = new ThreadCounter(7000);

Thread countera = new Thread(new ThreadStart(counter1.run));
Thread counterb = new Thread(new ThreadStart(counter2.run));
Thread counterc = new Thread(new ThreadStart(counter3.run));

countera.Start();
counterb.Start();
counterc.Start();

Console.ReadKey();
}
}

class ThreadCounter
{
private static int count = 0;
private int ms;
private static void Increment()
{
lock (typeof(ThreadCounter))
{
count++;
}
}

private static void Decrease()
{
lock (typeof(ThreadCounter))
{
count--;
}
}

private static int getCount()
{
lock (typeof(ThreadCounter))
{
return count;
}
}

public ThreadCounter(int ms)
{
Increment();
this.ms = ms;
}

public void run()
{
Thread.Sleep(ms);
Console.WriteLine(ms.ToString() + "毫秒任务结束");
Decrease();
if (getCount() == 0)
{
Console.WriteLine("-------所有任务结束-------");
}
}
}
方法二:Thread.Join方法
class Program
{
static void Main(string[] args)
{
ThreadJoin join1 = new ThreadJoin(1000);
ThreadJoin join2 = new ThreadJoin(3000);
ThreadJoin join3 = new ThreadJoin(7000);
Thread th1 = new Thread(new ThreadStart(join1.run));
Thread th2 = new Thread(new ThreadStart(join2.run));
Thread th3 = new Thread(new ThreadStart(join3.run));

ThreadJoin join = new ThreadJoin();
join.Join(new Thread[] { th1, th2, th3 });

Console.ReadKey();
}
}

class ThreadJoin
{
private int ms;
public ThreadJoin()
{

}

public ThreadJoin(int ms)
{
this.ms = ms;
}

public void run()
{
Thread.Sleep(ms);
Console.WriteLine(ms + "毫秒任务结束");
}

public void Join(object[] obj)
{
Thread[] ths = obj as Thread[];
foreach (Thread th in ths)
{
th.Start();
th.Join();
}
Console.WriteLine("所有线程结束");
}
}
转载自:http://developer.51cto.com/art/200908/147794.htm 自己做了修改
推荐:http://www.laikanxia.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 状态 线程 Thread