Thread常见方法
启动一个线程–start()
start()方法
**注意:**虽然创建Thread继承的对象调用start()方法和run()方法都能执行run()方法内部的函数块,但是如果只调用run方法无法创建一个新线程,只会在main线程中运行,运行完毕才会往下走
中断一个线程
在外部强制中断一个线程有两个方法
-
在外部提前创一个标志位,当需要中断线程时在外部更改标志位即可
public class Test { public static boolean isQuit = false;//标志位 public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> { while(!isQuit){ System.out.println("hello thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); Thread.sleep(4000); isQuit = true; System.out.println("线程中断"); } }
-
使用 Thread.currentThread().isInterrupted() 代替自定义标志位
Thread.currentThread()位静态方法,用于获取当前进程,类似this,如果需要中断则需要在外部调用interrupt()方法。
但是注意:interrupt方法对正在运行中的线程和阻塞(sleep)的线程作用效果是不同的,如果是正在运行,则标志位会立马置为false,如果在阻塞状态,线程会抛出InterruptedException,处理方法由异常处理决定。
如下面代码:
public class Test {
public static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while(!Thread.currentThread().isInterrupted()){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(4000);
t.interrupt();
System.out.println("线程中断");
}
}
在interrupt后由于线程处于阻塞状态,程序运行了e.printStackTrace();而并没有结束线程,如果要中断则需要加上break
这样的操作让我们有了更多选择:
- 直接中断线程
- 不管中断
- 稍后管理
如何选择需要依据具体情况决定
线程等待–join()
当我们需要线程走完以后再走下一步时,我们就需要使用join()方法。
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
for (int i = 0; i < 4; i++) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("线程开始");
t.start();
t.join();
System.out.println("线程结束");
}
}
方法 | 说明 |
---|---|
public void join() | 等待线程结束 |
public void join(long millis) | 等待线程结束,最多等 millis 毫秒 |
public void join(long millis, int nanos) | 同理,但可以更高精度 |
获取当前线程的引用
由于之前用过,这里不再多提
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}
线程的休眠–sleep()
方法 | 说明 |
---|---|
public static void sleep(long millis) throws InterruptedException | 休眠当前线程 millis 毫秒 |
public static void sleep(long millis, int nanos) throws InterruptedException | 可以更高精度的休眠 |
线程的状态
在操作系统中对PCB的状态有描述
但是java认为自带的状态并不合适,因此自己制定了一套状态
- NEW Thread对象创建出来了但是PCB没有创建,即还没有创建线程
- RUNNABLE 线程在运行状态
- TERMINATED PCB已经被消费但是Thread对象还在
- TIMEWATING 按照一定的时间进行阻塞(join(t), sleep(t))
- WAITING 特殊的阻塞状态(调用wait,join())
- BLOCKED 等待锁的时候进入的阻塞状态