java线程控制方法

一、中断线程


1.Thread.sleep()
让线程进入睡眠状态,放弃CPU的占用暂停若干毫秒
使用方法:

public class runable implements Runnable {
	@Override
	public void run() {
		for(int i=1;i<100;i++){
			System.out.println("first Runnable——>"+i);
			try {
				Thread.sleep(200);//设置睡眠时间为200毫秒,
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

  

2.Thread.yidld()

让线程放弃CPU的占用,但是继续抢占CPU

 


二、设置线程的优先级
默认优先级是5,最大优先级是10,最小优先级是1
1.getPriority()
得到当前进程的优先级
2.setPriority()
设置当前线程的优先级
使用方法:

public class main {

	public static void main(String[] args) throws InterruptedException {
		//实现接口
		runable ra=new runable();
		//生成Thread对象,并将接口对象作为参数
		Thread t=new Thread(ra);
		//sleep()方法使用
		t.sleep(200);
		//得到当前优先级
		int temp=t.getPriority();
		System.out.println("默认优先级:"+temp);
		//设置最高优先级并输出
		t.setPriority(Thread.MAX_PRIORITY);
		temp=t.getPriority();
		System.out.println("最高优先级:"+temp);
		//设置最低优先级,并输出
		t.setPriority(Thread.MIN_PRIORITY);
		temp=t.getPriority();
		System.out.println("最低优先级:"+temp);
	}
}

  

转载于:https://www.cnblogs.com/zxxiaoxia/p/4167202.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值