一、currentThread()方法
可以返回代码正在被那个线程调用的信息
public class ThreadTest extends Thread {
@Override
public void run() {
System.out.println("ThreadName 1:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest(1);
threadTest.start();
System.out.println("ThreadName 2:" + Thread.currentThread().getName());
}
}
运行结果
main方法是由一个叫main的线程调用的
run方法是由一个Thrad-0方法调用的
二、isAlive()方法
isAlive()方法的功能是判断当前线程是否处于活动状态。什么是活动状态呢?活动状态是指线程已经启动且尚未终止。线程处于正在运行或准备运行的状态,就认为线程是“存活”的
public class Thread2 extends Thread {
@Override
public void run() {
System.out.println("run.name=" + Thread.currentThread().getName());
}
public static void main(String args[]) {
try {
Thread2 thread2 = new Thread2();
thread2.start();
System.out.println("thread2.isAlive=" + thread2.isAlive());
Thread.sleep(1000);
System.out.println("thread2.isAlive=" + thread2.isAlive());
} catch (InterruptedException e) {
}
}
}
运行结果
注意:如果将线程对象以构造方式的方法传递给Thread对象那么使用isAlive可能会产生差异,产生这个差异的原因主要来自currentThread()方法
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive=" + Thread.currentThread().isAlive());
}
}
public class Main {
public static void main(String ages[]){
Thread1 t1=new Thread1();
Thread thread=new Thread(t1);
thread.start();
}
}
运行结果
运行结果第一个isAlive为false 为什么呢?让我们看看this代表的线程是么
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("run.name=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive=" + Thread.currentThread().isAlive());
}
}
运行结果
可以看出原来是因为两个不是同一个对象
三、getId();
该方法是获取线程的唯一ID标识
public class ThreadTest extends Thread {
String name;
public ThreadTest(String name){
this.name=name;
}
@Override
public void run() {
System.out.println(name +":"+ Thread.currentThread().getId());
}
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest("threadTest");
threadTest.start();
ThreadTest threadTest1 = new ThreadTest("threadTest1");
threadTest1.start();
ThreadTest threadTest2 = new ThreadTest("threadTest2");
threadTest2.start();
}
}
运行结果
四、sleep()方法
使当前线程在指定时间内“休眠”(这个太熟悉就不多解释了?)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
当然除了这几个简单的,还有很多常用的比如线程停止,暂停等方法,这个就放在后面再说吧
—————————————————————————————————————————
作者新手一枚,如有错漏,还望指正