Thread方法解析

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();
}
}
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值