微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐