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。