一、获取当前正在执行的线程
1. 使用Thread.currentThread方法获取
public class Main {
public static void main(String[] args) {
// 1. 获取当前正在执行的线程
Thread thread = Thread.currentThread();
// 2. 打印该线程
System.out.println(thread);
}
}
2. 打印结果
结果解释:Thread[线程名称, 线程优先级, 线程所属的线程组名称]
其中,线程优先级越高,获取CPU执行权的概率越大。
二、获取和设置线程的名称
1. 获取和设置线程的名称
public class Main {
public static void main(String[] args) {
// 1. 获取当前正在执行的线程
Thread thread = Thread.currentThread();
// 2. 获取并打印修改前名称
String currentName = thread.getName();
System.out.println("修改前名称:"+ currentName);
// 3. 重新设置线程名称
thread.setName("newMain");
// 4. 获取并打印修改后名称
String newName = thread.getName();
System.out.println("修改后名称:"+ newName);
}
}
注意:thread.setName() 使用了synchronized关键字,是个线程安全的方法。
2. 打印结果
三、获取和设置线程的优先级
1. 获取和设置线程的优先级
public class Main {
public static void main(String[] args) {
// 1. 获取当前正在执行的线程
Thread thread = Thread.currentThread();
// 2. 获取并打印修改前的优先级
int currentPriority = thread.getPriority();
System.out.println("修改前名优先级:"+ currentPriority);
// 3. 重新设置线程的优先级
thread.setPriority(10);
// 4. 获取并打印修改后的优先级
int newPriority = thread.getPriority();
System.out.println("修改后优先级:"+ newPriority);
}
}
2. 打印结果
四、run方法和start方法的区别
1. 位置
run方法和start方法都位于Thread类里面,但是run方法是重写的方法。
2. 类型
run方法不是同步方法,而start方法是同步方法(不会有线程安全问题)。
3. 作用
run方法的作用是存储任务代码,而start方法的作用是启动线程。
4. 线程数量
run方法不会产生新的线程,而start方法会产生一个新的线程。
5. 调用次数
run方法可以被调用无数次,而start方法只可以被调用一次。
五、线程睡眠sleep方法
1. 调用sleep方法
public class Main {
public static void main(String[] args) throws InterruptedException {
// 打印睡眠前时间
System.out.println("睡眠前:"+ LocalDateTime.now());
// 睡眠2000ms
Thread.sleep(2000);
// 打印睡眠后时间
System.out.println("睡眠后:"+ LocalDateTime.now());
}
}
2. 打印结果
注意:sleep还有一个重载方法,支持纳秒。
六、线程中断interrupt方法
1. 定义一个实现Runnable接口的对象
public class Task implements Runnable {
@Override
public void run() {
while (true) {
Thread thread = Thread.currentThread();
// 判断当前线程是否被中断
if (thread.isInterrupted()) {
// 结束循环
break;
}
System.out.println("线程正在执行中...");
}
System.out.println("线程被中断了!");
}
}
或者
public class Task implements Runnable {
@Override
public void run() {
while (true) {
// 判断当前线程是否被中断,并清除线程中断标记
if (Thread.interrupted()) {
// 结束循环
break;
}
System.out.println("线程正在执行中...");
}
System.out.println("线程被中断了!");
}
}
2. 在主函数中调用线程中断方法
public class Main {
public static void main(String[] args) throws InterruptedException {
// 创建任务实例
Task task = new Task();
// 创建线程
Thread thread =new Thread(task);
// 启动线程
thread.start();
// 使主线程休眠100毫秒
Thread.sleep(100);
// 调用线程中断方法(将线程标记为中断状态)
thread.interrupt();
}
}
3. 打印结果