Java线程的生命周期的详解
Java线程的生命周期的详解 对于多线程编程而言,理解线程的生命周期非常重要,本文就针对这一点进行讲解。 一、线程的状态 线程的存在有几种不同的状态,如下:
1、New状态 New状态是线程已经被创建,但是还未开始运行的状态。此状态通过调用线程的start()方法可让线程运行。 2、Runnable状态 Runnable状态可称为准备运行状态,也可称为队列,此状态通过调用线程的start()方法可让线程运行。 3、Running状态 如果一个线程正在执行中,那么它处于Running状态。 4、Dead状态 一旦某个线程进入了Dead状态,那么它就再也不能运行了。 5、Non runnable状态 某个正在运行的线程可转变到Non runnable状态,这取决于运行情况。 Java虚拟机JVM根据线程的优先级和调度原则执行线程。 二、线程调度器 在JVM中,线程调度器的实现通常基于以下两种策略:
线程调度器的实现与平台无关,因此线程的调度是不可预测的。 三、线程的优先级 JVM会为每一个新创建的线程分配一个优先级。
为了保存这些值,线程类有三个相应的变量:
一个线程首先会继承其父线程的优先级,每一个线程默认的优先级是5级(Normal优先级),主线程的默认优先级为5级。 可以通过setPriority(int priority)方法来设置线程的优先级。
用户定义的线程,其默认的线程名为Thread+序号,序号从0开始,比如第一个线程为Thread0。
实例 下面看一个例子: package demo.ch; public class UserThread extends Thread { UserThread() { super(); } UserThread(String name) { super(name); } public void run() { System.out.println("thread started running.."); } public static void main(String[] args) { UserThread thread1 = new UserThread("Thread1"); UserThread thread2 = new UserThread("Thread2"); System.out.println("Thread 1 initial name and priority"); System.out.println("name:" + thread1.getName()); System.out.println("priority:" + thread1.getPriority()); System.out.println("Thread 2 initial name and priority"); System.out.println("name:" + thread2.getName()); System.out.println("priority:" + thread2.getPriority()); System.out.println(""); thread1.setPriority(6); thread2.setPriority(9); System.out.println("Thread 1 initial name and priority"); System.out.println("name:" + thread1.getName()); System.out.println("priority:" + thread1.getPriority()); System.out.println("Thread 2 initial name and priority"); System.out.println("name:" + thread2.getName()); System.out.println("priority:" + thread2.getPriority()); System.out.println(""); thread1.start(); thread2.start(); for(int i=0; i<5; i++) System.out.println("main method i value: " + i); } } 输出结果: Thread 1 initial name and priority name:Thread1 priority:5 Thread 2 initial name and priority name:Thread2 priority:5 Thread 1 initial name and priority name:Thread1 priority:6 Thread 2 initial name and priority name:Thread2 priority:9 main method i value: 0 main method i value: 1 thread started running.. main method i value: 2 thread started running.. main method i value: 3 main method i value: 4 如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |