线程优先级练习记录

package cm;

public class test20180502Concurrency extends Thread {
	private int countdown = 5;
	private static int threadcount = 0;

	public test20180502Concurrency(int newPriority) {
		super("" + ++threadcount);//接受一个static参数,设置线程名称
		setPriority(newPriority);
		start();//start方法执行必要的线程初始化,并调用run方法
	}

	public String toString() {
		return "#" + getName() + ":" + countdown;//getname是Thread中的一个静态方法。
	}

	public void run() {
//		while(true) {
//			System.out.println(this);
//			if(--countdown==0) {
//				return;//跳出循环
//			}
//			yield();//给线程调度机制一个暗示,表示可以将cpu分配给其他线程了,但不一定保证被程序调度器采纳。
//			try {
//				sleep(100);//使得线程睡眠100毫秒。
//			} catch (InterruptedException e) {//抛出异常的原因是:当对此线程具有引用,并在这个引用上调用了interrupt()方法,那么就会抛出InterruptedException异常。
//				e.printStackTrace();
//			}
//		}
		
		
		//修改上面程序版本,为程序添加优先权。使得处于等待状态的高优先级线程先得到执行。
		while(true) {
			System.out.println(this);
			if(--countdown==0) {
				return;//跳出循环
			}
		}
		
		
	}

	public static void main(String[] args) {
		for(int i=0;i<5;i++) {
			//测试线程优先级。
			if(i<4) {
				new test20180502Concurrency(Thread.MIN_PRIORITY);//最小优先级
			}else {
				new test20180502Concurrency(Thread.MAX_PRIORITY);//最大优先级
			}
			
			//new test20180502Concurrency();//创建五个线程。观察他们的打印顺序,同时执行的。
			//这里并没有声明这个实例的引用,但是垃圾回收器不会回收这个对象,因为thread对象需要注册自己,在某个地方
			//有着对这个threead对象的引用。只有线程 离开了run方法的时候才会将这个对象清理掉。
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值