Thread类 API
currentThread()
返回当前正在执行的线程对象的引用。
关于currentThread和this
package ch01.test1;
public class MyThread extends Thread {
public MyThread() {
System.out.println("MyThread begin");
System.out.println("Thread.currentThread().getName()= "+Thread.currentThread().getName());
System.out.println("this.getName()="+ this.getName());
System.out.println("MyThread end");
}
@Override
public void run() {
super.run();
System.out.println("run begin");
System.out.println("Thread.currentThread().getName()= "+Thread.currentThread().getName());
System.out.println("this.getName()="+ this.getName());
System.out.println("run end");
}
}
class Test {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
Thread t1 = new Thread(myThread1);
t1.setName("A");
t1.start();
}
}
MyThread begin
Thread.currentThread().getName()= main
this.getName()=Thread-0
MyThread end
run begin
Thread.currentThread().getName()= A
this.getName()=Thread-0
run end
实际上new Thread(myThread1)会将myThread1绑定到一个pravite变量target上,在t1被执行的时候即t1.run()被调用的时候,它会调用target.run()方法,也就是说它是直接调用myThread1对象的run方法,再确切的说,在run方法被执行的时候,this.getName()实际上返回的是target.getName(),而Thread.currentThread().getName()实际上是t1.getName()。
isAilve()
测试线程是否处于“活动状态”。“活动状态”是指线程处于runnable状态。
sleep()
当前正在执行的线程休眠(暂停执行)为指定的毫秒数。
package ch01.test2;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println(this.currentThread().getName()+" begin");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.currentThread().getName()+" end");
}
}
class test2 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("begin = " + System.currentTimeMillis());
// 体会直接调用run方法和调用start方法的区别
// myThread.run();
myThread.start();
System.out.println("end = " + System.currentTimeMillis());
}
}
output1:直接调用run方法
begin = 1599622708757
main begin
main end
end = 1599622710757
-------------------------------
output2:调用start方法
begin = 1599622604015
end = 1599622604015
Thread-0 begin
Thread-0 end
getID()
获取线程的唯一标识