Thread常见的API

回顾:

在日常开发中我们常用实现Runnable接口,但是在Runnable接口中只有run方法,所以在启动线程的时候我们必须将Runnable对象转换成Thread类的对象,从而可以使用.start()方法来启动线程; Thread th1=new Thread(Runnable对象,线程名字);

接下来学习一下线程常见的API

一、设置线程的优先级 .setpriority()

注意:优先级只是一个建议,但不能百分百保证

th1.setpriority(10); //1-10

th2.setpriority(2);

二、线程休眠,就是暂停的意思,单位是毫秒 .sleep()

Thread.sleep(1000);

try {
               Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

三、依赖关系:强制执行、现场礼让

——>强制执行

join:强制执行调动join()的线程,阻塞当前正在执行的线程

实例

public class ThreadDemo implements Runnable{
    @Override
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
    //这里有两个线程一个是main主线程 一个是线程th1
    //
    public static void main(String[] args){
        ThreadDemo t1=new ThreadDemo();
        Thread th1=new Thread(t1,"T1");
        th1.start;
        
        for(int i = 0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
            if(i==3){
                th1.join();//当main线程正在执行时(执行到i=3时,th1强制抢夺执行)
            }
        }
    }
}

——>线程的礼让:

yield(),礼让仅仅是一种尽可能的事件,并不是百分百执行

public void run() {
        for(int i =0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
            if(i==3){
                Thread.yield();
                System.out.println("礼让。。。。");
            }
        }
    }

    //线程th1:执行“T1:数字”
    //线程main: 执行"main:数字"
    public static void main(String[] args) throws InterruptedException {
        ThreadDemo03 t1=new ThreadDemo03();
        Thread th1=new Thread(t1,"T1");
        th1.start();

        ThreadDemo03 t2=new ThreadDemo03();
        Thread th2=new Thread(t2,"T2");
        th2.start();

注意:并不是所有的线程都是通过start()启动,除了main()线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱穿风衣的土豆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值