码迷,mamicode.com
首页 > 编程语言 > 详细

Java并发学习之二——获取和设置线程信息

时间:2014-08-08 21:31:41      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:线程创建

本文是学习网络上的文章时的总结,感谢大家无私的分享。

Thread类的对象中保存了一些属性信息能够帮助我们辨别每一个线程,知道它的一些信息

ID:每个线程的独特标示;

Name:线程的名称;

Priority:线程对象的优先级。优先级别在1-10之间,1是最低级,10是最高级。

Status:线程状态。在java中,线程只有6种状态:new,runnable,blocked,waiting,time waiting terminated

现在写一个程序,将线程的信息保存到文件中方便查看

package chapter;

public class Calculator2 implements Runnable{

	private int number;
	public Calculator2(int number){
		this.number = number;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 10; i++) {
			System.out.printf("%s:%d*%d = %d\n",Thread.currentThread().getName(),number,i,i*number);
		}
	}
}

package chapter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.Thread.State;

public class Main2 {

	/**
	 * <p>
	 * </p>
	 * @author zhangjunshuai
	 * @date 2014-8-8 下午3:36:20
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Thread[] threads = new Thread[10];
		Thread.State[] status = new Thread.State[10];
		for (int i = 0; i < 10; i++) {
			threads[i] = new Thread(new Calculator2(i));
			if((i%2) == 0)
				threads[i].setPriority(Thread.MAX_PRIORITY);
			else
				threads[i].setPriority(Thread.MIN_PRIORITY);
			threads[i].setName("Thread"+i);
		}
		try{
			FileWriter file = new FileWriter(".\\xianchenglog1.txt");
			PrintWriter pw = new PrintWriter(file);
			for(int i =0;i<10;i++){
				pw.println("main: status of thread "+i+": "+threads[i].getState());
				status[i] = threads[i].getState();
			}
			
			for(int i =0;i<10;i++){
				threads[i].start();
			}
			boolean finish = false;
			while(!finish){
				for (int i = 0; i < 10; i++) {
					if(threads[i].getState()!=status[i]){
						writeThreadInfo(pw,threads[i],status[i]);
					}
				}
				finish = true;
			}
			pw.close();
		}catch(Exception e){
			
		}
		
		
	}
	private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {
		   pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
		
		   pw.printf("Main : Priority: %d\n",thread.getPriority());
		
		   pw.printf("Main : Old State: %s\n",state);
		
		   pw.printf("Main : New State: %s\n",thread.getState());
		
		   pw.printf("Main : ************************************\n");
		
		}


}

bubuko.com,布布扣bubuko.com,布布扣

Java并发学习之二——获取和设置线程信息,布布扣,bubuko.com

Java并发学习之二——获取和设置线程信息

标签:线程创建

原文地址:http://blog.csdn.net/junshuaizhang/article/details/38443315

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!