1、线程属性
Thread类包含几个属性,这些属性所表示的信息能帮助我们识别线程、观察其状态、控制其优先级等。这些线程包括如下几种:
ID: 该属性表示每个线程的唯一标识;
Name: 该属性存储每个线程的名称;
Priority: 该属性存储每个Thread对象的优先级。线程优先级分1到10十个级别,1表示最低优先级,10表示最高优先级。并不推荐修改线程的优先级,但是如果确实有这方面的需求,也可以尝试一下。
Status: 该属性存储线程的状态。线程共有六种不同的状态:新建(NEW)、运行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、限时等待(TIMED_WAITING)或者终止(TERMINATED)。线程的状态必定是其中一种。
2、代码实现
本例子展现了使用线程运行乘法口诀,获取和设置线程属性。线程类如下:
package com.xxx.util;
/**
* Created with IntelliJ IDEA.
* Date: 15-3-25
* Time: 上午8:40
* To change this template use File | Settings | File Templates.
*/
public class ThreadPrioritySet implements Runnable {
private int num;
public ThreadPrioritySet(int num){
this.num = num;
}
@Override
public void run() {
for(int i=1;i<10;i++){
System.out.printf("%s:%d*%d=%d\n",Thread.currentThread().getName(),num,i,i*num);
}
}
}
main类:
package com.xxx.util;
import java.io.*;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* Date: 15-3-25
* Time: 上午8:47
* To change this template use File | Settings | File Templates.
*/
public class ThreadPrioritySetMain {
public static void main(String[] args){
long startTime = new Date().getTime();
System.out.printf("*******************开始时间%d******************************\n",startTime);
Thread threads[] = new Thread[10];
Thread.State status[] = new Thread.State[10];
for(int i=1;i<10;i++){
threads[i] = new Thread(new ThreadPrioritySet(i));
if((i%2)==0){
threads[i].setPriority(Thread.MAX_PRIORITY);
}else {
threads[i].setPriority(Thread.MIN_PRIORITY);
}
threads[i].setName("Tread "+i);
}
PrintWriter printWriter = null;
File file = null;
try {
//System.getProperty("user.dir")是取得当前项目的根目录;
File filePath = new File(System.getProperty("user.dir")+"\\data\\");
if(!filePath.exists()){
filePath.mkdirs();
}
file = new File(filePath+"\\threadPrioritySet.txt");
if(!file.exists()){
file.createNewFile();
}
//可是第二个参数设置追加(true),默认不追加,即覆盖
FileWriter fileWriter = new FileWriter(file);
printWriter = new PrintWriter(fileWriter);
//BufferedWriter 提供缓冲,用以加速
//printWriter = new PrintWriter(new BufferedWriter(fileWriter));
for(int i=1;i<10;i++){
printWriter.println("Main:Status of Thread "+i+":"+threads[i].getState());
status[i] = threads[i].getState();
}
//启动线程
for(int i=1;i<10;i++){
threads[i].start();
}
boolean finish = false;
while (!finish){
for(int i=1;i<10;i++){
if(threads[i].getState()!=status[i]){//判断线程状态是否发生变化
System.out.println("+++++++++++start+++++++++++++"+i);
writeThreadInfo(printWriter,threads[i],status[i]);
System.out.println("+++++++++++end+++++++++++++"+i);
status[i] = threads[i].getState();
}
}
finish = true;
//判断线程是否TERMINATED,直到线程都运行完成,任何一个线程的状态发生变化,就会将它写入文件中
for(int i=1;i<10;i++){
//赋值运算,获取线程状态,如果不是TERMINATED,finish=false再进行while循环
finish = finish&&(threads[i].getState()== Thread.State.TERMINATED);
}
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}finally {
if(printWriter!=null){
printWriter.flush();
printWriter.close();//需要关闭才能写入
long endTime = new Date().getTime();
System.out.printf("*******************结束时间%d******************************\n",new Date().getTime());
System.out.printf("*******************耗时%d******************************\n", endTime - startTime);
//readThreadInfo(file);
}
}
}
private static int flagNum = 0;
/**
* 写入文件信息
* @param printWriter
* @param thread
* @param state
*/
private static void writeThreadInfo(PrintWriter printWriter,Thread thread,Thread.State state){
System.out.println("+++++++++ing+++++++++++"+(++flagNum));
printWriter.printf("*******************Name=%s****************************\n",thread.getName());
printWriter.printf("Main:Id:%d - Name:%s\n",thread.getId(),thread.getName());
printWriter.printf("Main:Priority:%d\n", thread.getPriority());
printWriter.printf("Main:Old State:%s\n", state);
printWriter.printf("Main:New State:%s\n", thread.getState());
printWriter.printf("*******************Name=%s****************************\n\n",thread.getName());
}
/**
* 读取文件输出控制台
* @param file
*/
private static void readThreadInfo(File file){
String str= null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
while((str=bufferedReader.readLine())!=null){
System.out.printf("%s\n", str);
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}finally {
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
if(fileReader!=null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
}
3、部分运行结果
(1)控制台结果
(2)文件结果
4、结论
高优先级的线程大致比低优先级的线程较早完成执行,只是大致。
Thread类有可以存储线程信息所需的所有属性。Java虚拟机使用线程优先级来每个时刻调度一个线程来使用CPU,并且根据线程的情况来设置其每个线程的状态。