Thread类 提供了控制线程的几个方法 构造函数 public Thread( string threadName public Thread( 重载run方法,定义要以多线程方式完成的工作。 Sleep(): makes thread inactive Interrupt(): interrupts a running thread sAlive o: checks status of a thread setName(): sets a thread's name ■Join(): Waits for this thread to finish (等待本线程停止) 2021/224 北京理工大学计算机系(共28页)
2021/2/24 北京理工大学计算机系(共28页) 6 Thread类 ◼ 提供了控制线程的几个方法 ◼ 构造函数: public Thread( String threadName ) public Thread() ◼ 重载 run方法,定义要以多线程方式完成的工作。 ◼ Sleep(): makes thread inactive ◼ Interrupt(): interrupts a running thread ◼ isAlive ():checks status of a thread ◼ setName(): sets a thread’s name ◼ Join(): – Waits for this thread to finish – (等待本线程停止)
多线程第二种方法 一个类实现 java. lang Runable接口即 可,同样实现一个 public void run(方 法 实例: EraserDemo 更复杂的实例: ThreadTest 21/2/24 北京理工大学计算机系(共28页)
2021/2/24 北京理工大学计算机系(共28页) 7 多线程第二种方法 ◼ 一个类实现java.lang.Runable接口即 可,同样实现一个public void run()方 法. ◼ 实例:EraserDemo ◼ 更复杂的实例:ThreadTest
线程的生命周期 ■ Thread的状态 Born:(创建) Thread was just created Ready:(就绪) Thread's start method invoked Thread can now execute Running:(运行) Thread is assigned a processor and running Dead state:(死亡) a Thread has completed or exited Eventually disposed of by system 21/2/24 北京理工大学计算机系(共28页)
2021/2/24 北京理工大学计算机系(共28页) 8 线程的生命周期 ◼ Thread的状态 – Born:(创建) ◼ Thread was just created – Ready:(就绪) ◼ Thread’s start method invoked ◼ Thread can now execute – Running :(运行) ◼ Thread is assigned a processor and running – Dead state:(死亡) ◼ Thread has completed or exited ◼ Eventually disposed of by system
线程状态转换体现了一个线程的生命周期 hta q uantum exp rat i n d isp at ch yield (a ssign a inte rupt p proce sson 〈 running ra ting see ping de ad bloc ked 21/2/24
2021/2/24 北京理工大学计算机系(共28页) 9 线程状态转换体现了一个线程的生命周期
线程状态转换示例 中断一个线程: InterruptDemo java 线程调用Seep进入睡眠状态,用 Interrupt方法中断它 ■需要仔细分析程序流程 21/2/24 北京理工大学计算机系(共28页)
2021/2/24 北京理工大学计算机系(共28页) 10 线程状态转换示例 ◼ 中断一个线程: InterruptDemo.java ◼ 线程调用Sleep进入睡眠状态,用 Interrupt方法中断它 ◼ 需要仔细分析程序流程