Java多线程之sleep()方法和getId()方法

sleep()方法

让当前正在执行的线程休眠(暂停执行)指定的毫秒数。

public class MyThread1 extends Thread {
    @Override
    public void run() {
        try{
            System.out.println("run threadName = " +this.currentThread().getName() + "begin");
            Thread.sleep(2000);
            System.out.println("run threadName = " +this.currentThread().getName() + "end");
        }catch (InterruptedException e ){
            e.printStackTrace();
        }
    }
}

public class MyThread1Test {
    public static void main(String[] args) {
        MyThread1 mt1 = new MyThread1();
        System.out.println("begin = " + System.currentTimeMillis());
        mt1.run();
        System.out.println("end = " + System.currentTimeMillis());
    }
}

run方法中,让线程休眠(暂停执行)2000毫秒,我们从运行结果中可以看到线程暂停了2秒。

public class MyThread2 extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("run threadName = "+ this.currentThread().getName() + " begin" + System.currentTimeMillis());
            Thread.sleep(2000);
            System.out.println("run threadName = "+ this.currentThread().getName() + " end " + System.currentTimeMillis());
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}


public class MyThread2Test {
    public static void main(String[] args) {
        MyThread2 mt2 = new MyThread2();
        mt2.setName("AAA");
        System.out.println("begin "+ System.currentTimeMillis());
        mt2.start();
        System.out.println("end "+ System.currentTimeMillis());
    }
}

 

从运行结果可以看到,main线程没有调用sleep方法,所以没有暂停,但是AAA线程的run方法中调用了sleep方法,所以AAA线程暂停了2000毫秒的时间。

getId()方法

返回线程的唯一标识。

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " " + Thread.currentThread().getId());
    }
}

public class GetIdTest {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        Thread runThread = Thread.currentThread();
        System.out.println(runThread.getName() + " " + runThread.getId());
    }
}

从运行结果上可以看到,main线程的唯一标识是1,自定义线程runThread对象的唯一标识是14。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值