线程的五个状态

setPriority(int newPriority) 更改线程的优先级
Static void sleep(long millis) 在指定的毫秒数内让当前正在执行的线程休眠
Void join() 等待该线程终止
Static void yield() 暂停当前正在执行的线程对象,并执行其他线程
Void interrupt() 中断线程
Boolean isAlive() 测试线程是否处于活动状态

线程的优先级
线程优先级有1–10表示,1最低,默认优先级为5
优先级高德线程获得CPU资源的概率较大
public class MyRunnable implements Runnable{

public void run() {
    for(int i=0;i<100;i++){
        System.out.println(Thread.currentThread().getName()+":"+i);
    }
}

}
测试类
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(),”线程a”);
Thread t2 = new Thread(new MyRunnable(),”线程b”);
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
线程的强制执行
让线程暂时休眠指定时长,线程进入阻塞状态
睡眠时间过后线程会再进入可运行状态
Public static void sleep(long millis)
Millis为休眠时长,以毫秒为单位
调用sleep()方法需处理InterruptedException异常
Join方法
创建类
public class MyRunnable implements Runnable{
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+”运行”+i);
}
}
}
测试类
public class TestJionDemo {
public static void main(String[] args) {
System.out.println(“—-线程强制执行—-“);
//1.创建线程对象
Thread temp = new Thread(new MyRunnable(),”temp”);
temp.start();
for(int i=0;i<20;i++){
//当主线程执行到i=5是,暂停主线程,让子线程temp执行,完毕之后,主线程在继续执行
if(i==5){
try {
temp.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"运行: "+i+"秒");
    }
}

}

线程的礼让
暂停当前线程,允许其他具有相同优先级的线程获得运行机会
该线程处于就绪状态,不转为阻塞状态
只提供一种可能,但是不能保证一定会让礼让实现
public class MyRunnable implements Runnable{
public void run() {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+”运行”+i);
//当i==3时,县城里让,当前线程将CPU资源让出
if(i==3){
Thread.yield();
System.out.print(“线程礼让: “);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
测试类
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(),”线程a”);
Thread t2 = new Thread(new MyRunnable(),”线程b”);
t1.start();
t2.start();
}
}

线程的五个状态
创建,就绪,阻塞,运行,死亡
线程调度的方法
setPriority(int grade)
sleep(long millis)
Join()
yield()

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值