1.多线程常用方法:
currentThread() : 获取当前执行的线程
getName() : 获取线程名称
setName() : 设置线程名称
sleep(long millis) : 是一个静态方法,使当前执行线程进入睡眠状态
join() /join(long millis) : 是一个实例方法,使当前执行线程进入阻塞状态
interrupt() : 中断阻塞状态的线程
isAlive() : 判断当前线程是否处于存活状态
yield() : 线程让步
2.线程的优先级(1-10)
默认优先级 5。优先级高并不意味着线程会优先执行,只不过更多的获取 cpu 的资源。
MIN_PRIORITY : 1
NORM_PRIORITY : 5
MAX_PRIORITY : 10
getPriority() : 获取线程的优先级
setPriority() : 设置线程的优先级
3.实例:
public class HelloThread4 implements Runnable{
int i = 0;
@Override
public void run() {
while(i <= 100){
System.out.println(Thread.currentThread().getName() + ": 优先级:" + Thread.currentThread().getPriority());
i++;
}
}
}
public class TestThread4 {
public static void main(String[] args) {
HelloThread4 ht4 = new HelloThread4();
Thread t4 = new Thread(ht4);
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
Thread.currentThread().setPriority(1);
for (int i = 100; i < 200; i++) {
System.out.println(Thread.currentThread().getName() + " 优先级为:" + Thread.currentThread().getPriority());
}
}
}