线程控制——创建、启动及终止
2012-01-31 14:13
204 查看
1、创建线程
2、启动线程
3、终止线程
如果想要一个进程结束,一种方法是让线程的入口函数执行完毕,但是在很多情况你下这种方式并不足以满足应用程序的需求。
1)Abort
当Abort方法被调用,它会向要终止的线程触发ThreadAbortException,然后线程被终止。示例如下:
运行结果如图:
2) Join
join方法阻塞调用线程直到指定的线程停止执行。
运行结果:
Thread thread = new Thread(new ThreadStart(SortAscending));
2、启动线程
thread.Start();
3、终止线程
如果想要一个进程结束,一种方法是让线程的入口函数执行完毕,但是在很多情况你下这种方式并不足以满足应用程序的需求。
1)Abort
当Abort方法被调用,它会向要终止的线程触发ThreadAbortException,然后线程被终止。示例如下:
class Program { static void Main(string[] args) { Thread thread = new Thread(Run); thread.Start(); Thread.Sleep(1000); thread.Abort(); Console.WriteLine("Aborted."); Console.ReadLine(); } static void Run() { try { Console.WriteLine("Run executing."); Thread.Sleep(5000); Console.WriteLine("Run completed."); } catch (ThreadAbortException ex) { Console.WriteLine("Caught thread abort exception."); } } }
运行结果如图:
2) Join
join方法阻塞调用线程直到指定的线程停止执行。
static void Main(string[] args) { Thread thread = new Thread(Run); thread.Start(); Thread.Sleep(1000); thread.Join(); Console.WriteLine("Joined."); Console.ReadLine(); } static void Run() { try { Console.WriteLine("Run executing."); Thread.Sleep(5000); Console.WriteLine("Run completed."); } catch (ThreadAbortException ex) { Console.WriteLine("Caught thread abort exception."); } } }
运行结果:
相关文章推荐
- Java —— 多线程笔记 一、线程创建、启动、生命周期、线程控制
- SE高阶(4):多线程(并发)—①创建启动方式和控制线程方法
- 线程的控制(创建、等待、终止)、分离线程
- 【Linux】线程(概念、特点、线程控制代码--创建/等待/终止、分离与结合属性)
- 线程的创建、启动和终止
- Java并发1——线程创建、启动、生命周期与线程控制
- 漫谈并发编程(二):java线程的创建与基本控制
- 线程的创建终止和生命周期
- mysql 启动 报错 线程意外终止
- linux内核启动(2)——2.2.创建和中止任务与内核线程
- pthread线程的终止退出 | 线程的大量创建
- Java多线程基础,线程的创建使用以及终止
- java多线程-概念&创建启动&中断&守护线程&优先级&线程状态(多线程编程之一)
- 详解Java多线程编程中线程的启动、中断或终止操作
- java线程基础巩固---创建并启动线程
- 【运动控制】创建线程执行缓冲区
- JAVA笔记13__创建线程/线程休眠/等待线程终止/线程中断/守护线程
- 浅析Java中线程的创建和启动
- Java线程:创建与启动
- 多线程入门-第一章-线程的创建与启动