线程的几种常用方法和与之对应的状态

一.线程的常用方法

1.线程的优先级

Thread thread = new Thread(myRunnable);
thread.setPriority(Thread.MAX_PRIORITY);//线程的优先级

MAX_PRIORITY优先级高,MIN的优先级低

2.睡眠当前线程

class MyRunnable implements Runnable{

    public void run() {
        for(int i=0;i<10;i++){
            System.out.println("新开的线程"+i);
        }
    }
}

public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.setPriority(Thread.MAX_PRIORITY);//线程的优先级
        thread.start();
        Thread.sleep(1000*10);//线程睡眠,想要哪个线程睡眠,在哪个线程使用改方法
        for(int i=0;i<10;i++){
            System.out.println("主线程"+i);
        }
    }
}

注意是Thread类去调用sleep方法

3.设置让步

线程让步就是让出cpu资源,重新回到就绪状态,还是可以重新竞争资源,不会像sleep方法一样线程进入阻塞状态

class MyRunnable implements Runnable{

    public void run() {
        for(int i=0;i<10;i++){
            System.out.println("新开的线程"+i);
        }
    }
}

public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.setPriority(Thread.MAX_PRIORITY);//线程的优先级
        thread.start();
        Thread.yield();//线程让步(让出cpu资源) 但是实际不能保证改线程让步,因为释放资源后他还是会重新竞争
        for(int i=0;i<10;i++){
            System.out.println("主线程"+i);
        }
    }
}

4.合并

t.join()

线程A合并进入线程B,B线程会进入阻塞状态直到线程A执行完毕。

class JoinThread implements Runnable{

    public void run() {
        for(int i=0;i<10;i++){
            System.out.println("新开的线程"+i);
        }
    }
}


public class JoinTest {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("=====主线程开始=====");
        Thread t = new Thread(new JoinThread());
        t.start();
        t.join();
        System.out.println("=====主线程结束=====");
    }
}

5.守护线程

线程A在主线程中设置为守护线程,当主线程结束时,不管线程A是否执行完,线程A也会结束

class DemanThread implements Runnable{

    public void run() {
        for(int i=0;i<100;i++){
            System.out.println("新开的线程"+i);
        }
    }
}
public class DemanTest {
    public static void main(String[] args) {
        Thread t = new Thread(new DemanThread());
        t.setDaemon(true);
        t.start();
        for(int i=0;i<30;i++){
            System.out.println("主线程"+i);
        }
    }
}

二.线程状态

new的时候为new

start后转为runnable

获取到cpu资源转为running

yeild让步使running状态退回runnable状态

join,sleep均可使线程阻塞,从running转为blocked

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值