Thread类的常用方法
join简单使用
我们在T1线程的环境下,调用T2线程的join方法,那么T1线程将会等待T2线程结束后继续执行。也可以传入指定的等待时间,等待时间过后,不管T2线程有没有结束,T1线程将进行执行。
代码如下:
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
System.out.println("t1 start~");
Thread.sleep(1000);
System.out.println("t1 end~");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1");
t1.start();
System.out.println("main start~");
t1.join();
System.out.println("main end~");
}
sleep简单使用
让当前线程休眠指定的时间,同时让出CPU给其它线程。自身将处于阻塞状态。
join和sleep的相同点
1.调用这两个方法的线程对象都会处于等待状态。
2.都可能抛出InterruptedException异常
interrupt
调用此方法时:
若线程处于阻塞状态(调用了sleep,join,wait),则会抛出InterruptException异常。并清除打断标记。(一个boolean变量,标识此线程是否被打断)
若线程处于正常运行状态,则设置打断标志为true
实例代码(模拟每隔一段时间进行数据收集等操作):
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
while (true) {
boolean interrupted = Thread.currentThread().isInterrupted();
if (interrupted) {
System.out.println("被打断后的逻辑处理");
break;
}
try {
Thread.sleep(100);
System.out.println("正常的逻辑处理");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, "t1");
t1.start();
Thread.sleep(1000);
t1.interrupt();
}
yield
试图让出CPU的使用权,但不保证一定能让出。
当前线程由Running变成Runnable.