方法名 作用
setName() 设置线程的名字
getName() 返回线程的名字
sleep(int x) 使线程休眠,线程进入阻塞状态
start() 启动线程
run() 该方法中可以编写线程需要完成的工作
setPriority(int priority) 设置线程的优先级,数字越大,优先级越高
getPriority() 获取线程优先级
interrupt() 打断线程,当打断的线程的状态为阻塞时,相当于唤醒该线程(由阻塞变为就绪),其打断标记位为false;如果打断的是一个正常运行的线程,该线程的打断标记位为true,并且该线程并不会停止运行
yield() 线程的让步,让cpu先执行其他线程,让步后的线程进入就绪状态,不一定成功(因为调度器可能还是执行该线程)
join() 线程插队,插队一旦成功,一定会先执行完插队的线程。一般用于线程间的同步
isInterrupt() 获取线程的打断标记位
1
2
3
4
5
6
7
8
9
10
11
12
public void testInterrupt() throws InterruptedException {
Thread.currentThread().setName("main");
Thread t1 = new Thread(() -> {
while(true){
System.out.println("hello");
}
},"t1");
t1.start();
Thread.sleep(1000);
System.out.println("interrupt");
t1.interrupt();
}

image-20240310171825357

​ 可以发现,t1即使被打断了,依然会继续执行,似乎interrupt对该线程没有影响。因此需要根据打断标记位来退出循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void testInterrupt() throws InterruptedException {
Thread.currentThread().setName("main");
Thread t1 = new Thread(() -> {
while(true){
boolean interrupted = Thread.currentThread().isInterrupted();
if(interrupted){
break;
}
System.out.println("hello");
}
},"t1");
t1.start();
Thread.sleep(1);
System.out.println("interrupt");
t1.interrupt();

image-20240310172224776