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

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

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");
		
		}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值