在多线程Thread中有两个方法, sleep()和interrupt()
一、sleep方法
返回值 | 方法 | 使用描述 |
static void | sleep(long millis) | 使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行),具体取决于系统定时器和调度程序的精度和准确性。 |
static void | sleep(long millis, int nanos) | 导致正在执行的线程以指定的毫秒数加上指定的纳秒数来暂停(临时停止执行),这取决于系统定时器和调度器的精度和准确性。 |
使用该方法时, 需要处理InterruptedException异常, 也可以直接抛出, 但是一般都会把它处理掉.
try {
Thread.sleep(long millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
二、interrupt
返回值 | 方法 | 使用描述 |
void | interrupt() | 中断这个线程 |
拓展方法
返回值 | 方法 | 使用描述 |
static boolean | interrupted() | 测试当前线程是否中断 |
boolean | isInterrupted() | 测试这个线程是否被中断 |
三、代码演示
package com.softeem.wolf.thread;
/**
* Created by 苍狼
* Time on 2022-09-08
*/
public class ThreadTest02 {
public static void main(String[] args) {
Thread t1 = new Thread(){
@Override
public void run() {
System.out.println("AA:惊雷,这通天修为....");
try{
Thread.sleep(1000000);
}catch(InterruptedException inter){
inter.printStackTrace();
System.out.println("AA中断了....");
}
System.out.println("BB,你唱的啥玩意啊....");
}
};
Thread t2 = new Thread(){
@Override
public void run() {
System.out.println("BB:你唱的啥?");
for (int i = 0; i < 5; i++) {
System.out.println("BB:无所谓...");
try{
Thread.sleep(1000);
}catch (InterruptedException inter) {
inter.printStackTrace();
}
}
System.out.println("BB:唱完了");
t1.interrupt();
}
};
t1.start();
t2.start();
}
}
运行结果