Java并发编程学习2

通过这段代码可以了解线程各个阶段的状态:

package Test;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.State;

public class MyTest {
	
final private static int threadNum = 10;
	
public static void main(String[] args){
	Thread threads[] = new Thread[10];
	
	PrintWriter pw = null;
	Thread.State status[] = new Thread.State[10];
	FileWriter fileWriter = null;
	try {
		fileWriter = new FileWriter("log.txt");
		pw = new PrintWriter(fileWriter);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	for (int i = 0; i < threadNum; i++) {
		Caculator caculator = new Caculator(i);
		threads[i] = new Thread(caculator);
		if (i%2 == 0 ) {
			threads[i].setPriority(Thread.MAX_PRIORITY);
		}
		else {
			threads[i].setPriority(Thread.MIN_PRIORITY);
		}
		threads[i].setName("thread"+i);
	}
	
	for (int i=0; i<threadNum; i++){
		   pw.println("Main : Status of Thread "+i+" : " +threads[i].getState());
		   status[i]=threads[i].getState();
		   threads[i].start();
		}
	
	boolean finish=false;
	while (!finish) {
	   for (int i=0; i<threadNum; i++){
	      if (threads[i].getState()!=status[i]) {
	          writeThreadInfo(pw, threads[i],status[i]);
	          status[i]=threads[i].getState();
	      }
	   }

	   finish=true;
	   for (int i=0; i<10; i++){
	      finish=finish && (threads[i].getState()==State.TERMINATED);
	   }
	}
	
	pw.close();
	try {
		fileWriter.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

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

线程类:

package Test;

public class Caculator implements Runnable{
private int number;
public Caculator(){
	number = 0;
}
public Caculator(int num){
	number = num;
}

public void run() {
	for(int i=0; i<10;++i){
		System.out.printf("i=%d,thread:%s.\n",i,Thread.currentThread().getName());
	}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值