java笔记--查看和修改线程的优先级

查看和修改线程的优先级

java中每一个线程都有优先级属性,在默认情况下,新建的线程的优先级与创建该线程的线程优先级相同。
每当线程调度器选择要运行的线程时,通常选择优先级较高的线程。

注:线程的优先级是高度依赖于操作系统的,而且Sun对于不同的操作系统提供的虚拟机并不完全相同

--如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3893981.html "谢谢-- 

java JVM将线程的等级分为10级,MIN_PRIORITY为1级,MAX_PRIORITY为10级
对于main线程,它的默认优先级是5,最好不要修改线程的默认优秀级。
如果线程中有几个高优先级的线程,运行时优先选择这些线程运行;
若还有低优先级的线程,就会出现"饥饿"状态,即低优先级的线程基本不会被执行

Thread类与线程优先级相关的属性和方法:

MAX_PRIORITY : 线程可以具有最高优先级
MIN_PRIORITY : 线程可以具有的最低优先级
NORM_PRIORITY : 分配给线程的默认优先级
getPriority() : 获得线程的优先级
setPriority() : 修改线程的优先级

代码实例:

package com.xhj.thread;

import java.util.Scanner;
/**
* 查看和修改线程的优先级
*
* @author XIEHEJUN
*
*/
public class ModifyThreadPriority {

/**
* 获取并打印输出当前所有运行中的线程,包括(线程ID,线程名称,线程优先级)
*
* @return
*/
public static Thread[] getThreads() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
Thread[] threads = new Thread[group.activeCount()];
group.enumerate(threads);
System.out.println("线程ID\t" + "线程名称\t" + "线程优先级");
for (Thread thread : threads) {
System.out.println(thread.getId() + "\t" + thread.getName() + "\t"
+ thread.getPriority());
}
return threads;
}

/**
* 数据输入入口
*
* @return
*/
public static String input() {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
return str;
}

/**
* 修改线程优先级
*
* @param threads
*/
public static void modifyPriority(Thread[] threads) {
System.out.println("请输入您要修改的线程的ID");
int i = Integer.parseInt(input());
int count = -1;
for (Thread thread : threads) {
if (thread.getId() == i) {
System.out.println("请输入您要修改成的优先级别:");
int priroty = Integer.parseInt(input());
thread.setPriority(priroty);
break;
} else {
count++;
}
}
if (count == threads.length - 1) {
System.out.println("找不到您要的线程");
}
getThreads();

}

public static void main(String[] args) {
modifyPriority(getThreads());

}

}

posted @ 2014-08-20 09:24  Liape  阅读(2520)  评论(0编辑  收藏  举报