Java的知识点30——线程的优先级、终止线程的典型方式、获取线程基本信息的方法
线程的优先级 1-10
1. NORM_PRIORITY 5 默认
2. MIN_PRIORITY 1
3. MAX_PRIORITY 10
注意:优先级低只是意味着获得调度的概率低。并不是绝对先调用优先级高后调用优先级低的线程。
使用下述方法获得或设置线程对象的优先级。
• int getPriority();
• void setPriority(int newPriority);
/*** 线程的优先级 1-10* 1. NORM_PRIORITY 5 默认* 2. MIN_PRIORITY 1* 3. MAX_PRIORITY 10* * 概率: 不代表绝对的优先级顺序* @author Administrator**/ public class PriorityTest {public static void main(String[] args) {System.out.println(Thread.currentThread().getPriority()); //5MyPriority mp=new MyPriority();Thread t1=new Thread(mp,"1");Thread t2=new Thread(mp,"2");Thread t3=new Thread(mp,"3");Thread t4=new Thread(mp,"4");Thread t5=new Thread(mp,"5");Thread t6=new Thread(mp,"6");//设置优先级在启动前t4.setPriority(Thread.MAX_PRIORITY);t5.setPriority(Thread.MAX_PRIORITY);t6.setPriority(Thread.MAX_PRIORITY);t1.setPriority(Thread.MIN_PRIORITY);t2.setPriority(Thread.MIN_PRIORITY);t3.setPriority(Thread.MIN_PRIORITY);t1.start();t2.start();t3.start();t4.start();t5.start();t6.start();} }class MyPriority implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"-->"+ Thread.currentThread().getPriority()); //5Thread.yield();}}线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕;如:后台记录操作日志、监控内存使用
守护线程:是为用户线程服务的;jvm停止 不用等待守护线程执行完毕
默认:用户线程jvm等待用户线程执行完毕才会停止
终止线程的典型方式
终止线程我们一般不使用JDK提供的stop()/destroy()方法(它们本身也被JDK废弃了)。通常的做法是提供一个boolean型的终止变量,当这个变量置为false,则终止线程的运行。
public class TestThreadCiycle implements Runnable {String name;boolean live = true;// 标记变量,表示线程是否可中止;public TestThreadCiycle(String name) {super();this.name = name;}public void run() {int i = 0;//当live的值是true时,继续线程体;false则结束循环,继而终止线程体;while (live) {System.out.println(name + (i++));}}public void terminate() {live = false;}public static void main(String[] args) {TestThreadCiycle ttc = new TestThreadCiycle("线程A:");Thread t1 = new Thread(ttc);// 新生状态t1.start();// 就绪状态for (int i = 0; i < 10; i++) {System.out.println("主线程" + i);}ttc.terminate();System.out.println("ttc stop!");} }暂停线程执行常用的方法有sleep()和yield()方法,这两个方法的区别是:
1. sleep()方法:可以让正在运行的线程进入阻塞状态,直到休眠时间满了,进入就绪状态。
2. yield()方法:可以让正在运行的线程直接进入就绪状态,让出CPU的使用权。
获取线程基本信息的方法
* isAlive() 表示线程是否还活着
* Thread.currentThread() 表示当前线程
* setName("") setName("") 表示代理对象的名称
/*** 其他方法* isAlive() 表示线程是否还活着* Thread.currentThread() 表示当前线程* setName("") setName("") 表示代理对象的名称 * @author Administrator**/ public class InfoTest {public static void main(String[] args) throws InterruptedException {System.out.println(Thread.currentThread().isAlive());//设置名称:真实角色+代理角色MyInfo info=new MyInfo("战斗机");Thread t=new Thread(info);t.setName("公鸡");t.start();Thread.sleep(1000);System.out.println(t.isAlive());} } class MyInfo implements Runnable{private String name;public MyInfo(String name) {super();this.name = name;}@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"-->"+name);}}
总结
以上是生活随笔为你收集整理的Java的知识点30——线程的优先级、终止线程的典型方式、获取线程基本信息的方法的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 计算机网络知识点2——数据交换、码分多路
- 下一篇: Java的知识点31——线程同步