1.线程中断
(1)通过thread 对象调用 interrupt 方法通知线程中断.
(2). thread 收到通知的方式有两种:
- 如果线程调用了 wait/join/sleep 等方法而阻塞挂起,则以 InterruptedException 异常的形式通知,清除中断标志
- 否则,只是内部的一个中断标志被设置,thread 可以通过
(设置中断标志:true; 清除中断标志:false)
①. Thread.interrupted() 判断当前线程的中断标志被设置,清除中断标志
② Thread.currentThread().isInterrupted() 判断指定线程的中断标志被设置,不清除中断标志
具体方法:
public void interrupt() :中断对象关联的线程,如果线程正在阻塞,则以异常方式通知,否则设置标志位
public static boolean interrupted() :判断当前线程的中断标志位是否设置,调用后清除标志位
public boolean isInterrupted(): 判断对象关联的线程的标志位是否设置,调用后不清除标志位
注意:调用interrupt() 方法,只是通知线程要终止, 至于线程是否终止,需要线程自行判断.
public static void main(String[] main) throws InterruptedException {
Thread t= new Thread( new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().isInterrupted());
}
}
});
t.start();
Thread.sleep(1);
t.interrupt();
}
-------
2.线程等待
当需要等一个线程执行完后,才能进行接下来的操作时,就得调用 join() 方法,等待一个线程结束.
方法:
public void join() 等待线程结束
public void join(long millis) 等待线程结束,最多等 millis(毫秒)
public void join(long millis, int nanos) 同理,但可以更高精度
public static void main(String[] args) throws InterruptedException {
Thread t1= new Thread(()->{
System.out.println("A");
});
Thread t2= new Thread(()->{
System.out.println("B");
});
Thread t3= new Thread(()->{
System.out.println("C");
});
t1.start();
t1.join();
等t1执行结束后,再执行t2;下同.//所以ABC会按顺序打印
t2.start();
t2.join();
t3.start();
t3.join();
}
如果不加 join() 方法 ,那么ABC就不是按顺序打印了
3.线程休眠
注意: 因为线程的调度是不可控的,所以,这个方法只能保证线程休眠时间是大于
等于所设置的休眠时间的。
public static void main(String[] args) throws InterruptedException {
System.out.println(System.currentTimeMillis());
Thread.sleep(3 * 1000);//休眠3000毫秒;
System.out.println(System.currentTimeMillis());