20220521_线程最常用的方法

本文展示了如何在Java中创建线程并使用`Thread.currentThread()`获取当前线程,以及通过`Thread.sleep()`实现线程休眠。示例包括自定义线程类和线程休眠的用法,详细解释了线程执行流程。

线程类

public class MyThread extends Thread{
    public MyThread() {
    }

    public MyThread (String name){
        super(name);

    }

    @Override
    public void run() {
        for (int i = 1; i < 6; i++) {
            System.out.println(Thread.currentThread().getName()
                    +" thread is running~~~"+i);

        }
    }
}

执行类
涉及方法,getName,setName,Thread.currentThread()

public class ThreadApiDemo1 {
    public static void main(String[] args) {
        Thread th1 = new MyThread();
        th1.start();
        System.out.println(th1.getName());

        Thread th2 = new MyThread();
        th2.start();
        System.out.println(th2.getName());

        Thread th3 = new MyThread();
        th3.setName("No.3");
        th3.start();

        Thread th4 = new MyThread("No.4");
        th4.start();

        Thread th = Thread.currentThread();
        String thName = th.getName();

        for (int i = 1; i < 6; i++) {
            System.out.println(thName+" thread is running~~~"+i);
        }

    }
}

线程休眠方法

public class ThreadApiDemo2 {
    public static void main(String[] args) throws InterruptedException {

        Thread th = Thread.currentThread();
        String thName = th.getName();

        for (int i = 1; i < 6; i++) {
            System.out.println(thName+" thread is running~~~"+i);
            if (i == 3){
                Thread.sleep(3000);
            };
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值