1、方法列表与解释
activeCount(): 获取当前线程的线程组和当前线程的线程组作为祖先的任何其他线程组中活动线程的数量。
currentThread() : 获取当前线程。
dumpStack() : 调试时将当前线程的堆栈跟踪打印到标准错误流。
getId() : 获取当前线程ID。
holdsLock(Object obj) : 判断当前线程是否拥有对象锁。
interrupted():判断当前线程是否中断。
sleep(long millis, int nanos):睡眠当前线程并不会放开锁。
yield():向调度程序提示当前线程愿意让出当前使用的处理器。
getPriority():获取优先级。
getThreadGroup():获取线程组。
isAlive():是否是启动状态。
isDaemon():是否是一个守护线程。
setDaemon():设置为守护线程。
join():等待加入的线程。
wait():睡眠并放开锁,给其他的线程使用。
notify():通知需要这把锁的wait()线程,使之唤醒。
setName(String name):设置线程名称,不能为空。
setPriority(int newPriority):设置优先级。
start():启动线程。
2、守护线程示例代码:
public class App {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Thread1());
Thread thread2 = new Thread(new Thread2());
System.out.println(Thread.currentThread().isDaemon());
System.out.println(thread1.isDaemon());
thread2.setDaemon(true);
thread1.start();
thread2.start();
System.out.println(thread2.isDaemon());
thread1.join();
thread2.join();
System.out.println("App2");
}
public static class Thread1 implements Runnable {
public void run() {
System.out.println("thread1");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class Thread2 implements Runnable {
public void run() {
System.out.println("thread2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}