每个线程在运行时都要经历新生、就绪、运行、阻塞和死亡5种状态,线程从新生到死亡的状态变化过程称为生命周期。
*线程的状态转换
package day11; class Ath implements Runnable { Thread father,son; public Ath() { father=new Thread(this); son=new Thread(this); father.setName("爸爸"); son.setName("小明"); } public void run() { if(Thread.currentThread()==son) try { System.out.println(son.getName()+"正在玩游戏,不学习"); Thread.sleep(2000*60*60); } catch(InterruptedException e) { System.out.println(son.getName()+"的电脑被爸爸关掉了"); } else if(Thread.currentThread()==father) { for(int i=5;i>=1;i--) { System.out.println("别玩了"+i+"秒"); try { Thread.sleep(1000); } catch(InterruptedException e) { } } son.interrupt(); } } } public class ThreadDemo1 { public static void main(String[] args) { Ath a=new Ath(); a.son.start(); a.father.start(); } }运行结果:
小明正在玩游戏,不学习
别玩了5秒
别玩了4秒
别玩了3秒
别玩了2秒
别玩了1秒
小明的电脑被爸爸关掉了
以上结果每过一秒显示一条。Ath类实现Runnable接口并在构造方法中生成了线程对象father和son,在main主线程中启动之,son线程在运行后就进入了2小时的休眠(sleep(1000*60*60)),而father线程运行后循环了5次就执行了son.interrupt()语句将son线程中断使之返回就绪队列继续执行。
参考书籍:《Java程序设计》曹大有等,亦是笔记来源。