Thread类的应用
来源:互联网 发布:stoll制版程序员招 编辑:程序博客网 时间:2024/05/17 05:05
Thread.join方法
join方法只有在线程结束时才继续执行下面的语句(会依次执行)。可以对每一个线程调用它的join方法,但要注意,这个调用要在另一个线程里,而不要在主线程,否则程序会被阻塞的。在调用join前先要Start开启线程
看一个阻塞主线程的方法
static void Main(string[] args) { int ms = 1000; Thread thread1 = new Thread(Mymethod); thread1.Name = "thread1"; Thread thread2 = new Thread(Mymethod); thread2.Name = "thread2"; Thread thread3 = new Thread(Mymethod); thread3.Name = "thread3"; for (int i = 0; i < 10; i++) { Console.WriteLine("主线程工作了 " + i.ToString() + " 次."); if (i == 5) { Thread[] tr = new Thread[] { thread1, thread2, thread3 }; foreach (Thread t in tr) { t.Start(ms); t.Join(); } } } Console.ReadKey(); } private static void Mymethod(object obj) { Thread.Sleep(Int32.Parse(obj.ToString())); Console.WriteLine(Thread.CurrentThread.Name.ToString() + "结束任务用时:" + obj); }
执行效果如图
把Join不放在主线程中执行
class Program
{
static void Main(string[] args)
{
int ms = 1000;
Thread thread1 = new Thread(Mymethod);
thread1.Name = "thread1";
Thread thread2 = new Thread(Mymethod);
thread2.Name = "thread2";
Thread thread3 = new Thread(Mymethod);
thread3.Name = "thread3";
thread1.Start(100);
thread2.Start(2000);
thread3.Start(3000);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("主线程工作了 " + i.ToString() + " 次.");
Thread.Sleep(1000);
}
Thread joinThread = new Thread(JoinAllThread);
joinThread.Start(new Thread[] { thread1, thread2, thread3 });
Console.ReadKey();
}
private static void JoinAllThread(object obj)
{
Thread[] threads = obj as Thread[];
foreach (Thread t in threads)
{
t.Join();
}
}
private static void Mymethod(object obj)
{
Thread.Sleep(Int32.Parse(obj.ToString()));
Console.WriteLine(Thread.CurrentThread.Name.ToString() + "结束任务用时:" + obj);
}
}
执行效果如图
定义一个线程类
我们可以将Thread类封装在一个MyThread类中,以使任何从MyThread继承的类都具有多线程能力。MyThread类的代码如下
class Program : MyThread
{
static void Main(string[] args)
{
Program nt = new Program();
nt.start();
Console.ReadKey();
}
override public void run()
{
Console.WriteLine("使用MyThread建立并运行线程");
}
}
abstract class MyThread
{
Thread thread = null;
abstract public void run();
public void start()
{
if (thread == null)
thread = new Thread(run);
thread.Start();
}
}
- Thread类的应用
- C# Thread类的应用
- C# Thread类的应用
- C# Thread类的应用
- boost::thread的简单应用
- boost 中 thread 的应用
- Thread和Runnable的应用
- C#线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- #线程系列讲座(2):Thread类的应用
- C#线程系列讲座(2):Thread类的应用
- java中继承Thread类的实际编码应用
- C#中Thread类应用
- 南大软院大神养成计划第十四天
- Android AutoLayout全新的适配方式 堪称适配终结者
- 单例模式
- 大话设计模式之面向对象基础篇(三)
- linux 系统11步yum安装MySQL数据库
- Thread类的应用
- oracle 11g角色管理
- Java - 认识 JDBC
- 直接跳转到appStore
- 数据库 关系代数 投影概念理解
- RTSP二次开发包
- django开发要点-URL的配置2,在urlconf中增加参数
- 普通方法验证 邮箱正确性
- mysql支持的数据类型简介