Java线程基础
线程状态
new:新建线程状态,线程被new出来,但未调用start方法。
runnable:可运行状态,调用start后,线程进入runnable状态,包括running(获得cpu使用权并获得cpu时间片,正在被cpu执行)和ready(获得cpu使用权但未抢到cpu时间片,等待被cpu执行)。
blocked:阻塞状态,当线程遇到加锁的代码块,但未获得锁的时候,线程进入阻塞。
waiting:等待状态,线程调用Object.wait(),Thread.join(),LockSupport.park()会进入waiting状态
timed_waiting:超时等待,和waiting状态的区别是会设置一个超时时间,超时时间过了后会直接返回执行。
terminated:线程执行完成
线程转换图
线程状态转换代码示例
public static void main(String[] args) throws Exception {
//状态切换 - new -> runnable -> terminated
System.out.println("#######状态切换 - new -> runnable -> terminated######################");
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("执行了!thread1当前状态:"+Thread.currentThread().getState());
}
});
System.out.println("未调用start,thread1的状态:"+thread1.getState());
thread1.start();
System.out.println("调用start后,thread1的状态:"+thread1.getState());
Thread.sleep(100);
System.out.println("运行完后,thread1的状态:"+thread1.getState());
System.out.println();
}
public static void main(String[] args) throws Exception {
Thread current = Thread.currentThread();
//状态切换 - timed_waiting
System.out.println("#######状态切换 - timed_waiting####################");
Thread thread2 = new Thread(()->{
try {
/*Thread.sleep(long millis)、Thread.join(long millis)、LockSupport.parkUntil(long deadline)、
LockSupport.parkNanos(long nanos)、Object.wait(long timeout)都可以让线程进入timed_waiting状态*/
Thread.sleep(200);
//current.join(200);
//LockSupport.parkNanos(200000000L);
System.out.println("睡眠500ms后,执行了!thread2状态:"+Thread.currentThread().getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("未调用start,thread2的状态:"+thread2.getState());
thread2.start();
System.out.println("调用start后,thread2的状态:"+thread2.getState());
Thread.sleep(100);
System.out.println("100ms后,thread2状态:"+thread2.getState());
Thread.sleep(300);
System.out.println("300ms后,thread2状态:"+thread2.getState());
System.out.println();
}
public static Object object = null;
public static void main(String[] args) throws Exception {
//状态切换 - waiting、blocked
System.out.println("#######状态切换 - waiting、blocked####################");
new apprun().waitNotifyTest();
}
public void waitNotifyTest () throws Exception {
Thread thread1 =
new Thread(()->{
synchronized (this){
while (object == null) {
try {
/*Thread.join()、LockSupport.park()、Object.wait()都可以让线程进入timed_waiting状态*/
this.wait();
System.out.println("状态5:"+Thread.currentThread().getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ok");
}
});
System.out.println("状态1:"+thread1.getState());
thread1.start();
System.out.println("状态2:"+thread1.getState());
Thread.sleep(500);
object = new Object();
synchronized (this) {
System.out.println("状态3:"+thread1.getState());
/*Object.wait()、Object.waitAll()、LockSupport.unpark(Thread)都可以唤醒线程*/
this.notifyAll();
//状态4为blocked状态而非waiting状态,是因为thread1虽然被唤醒了,但同步代码块还没执行完成,所以进入阻塞态
System.out.println("状态4:"+thread1.getState());
}
Thread.sleep(20);
System.out.println("状态6:"+thread1.getState());
}
线程中止
线程中止的三种方式:通过Thread.stop()强制中止,通过Thread.interrupt()中止线程,通过状态位的方式来中止线程。
stop强制中止线程
不建议使用,强制中止线程会破坏线程安全性。
下面代码执行,得出的结果是i=1,j=0,同步代码块的原子性被破坏了,导致不符合预期结果。
public static void main(String[] args) throws InterruptedException {
StopThread stopThread = new StopThread();
stopThread.start();
Thread.sleep(100);
stopThread.stop();
while (stopThread.isAlive()) {
//保证线程执行完毕
}
stopThread.print();//输出结果为i=1,j=0,而非i=1,j=1
}
public class StopThread extends Thread {
private int i = 0, j = 0;
@Override
public void run() {
synchronized (this) {
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
j++;
}
}
public void print(){
System.out.println("i="+i+",j="+j);
}
}
interrupt中止线程
interrupt可以改变线程的中断状态,但它并不会中断线程的运行。 如果我们要通过interrupt中止线程,可以通过isInterrupted()或者interrupted()获取中断状态,逻辑判断退出。
interrupt在使用的时候会有两种情况:
1、当碰到线程被挂起(如wait,sleep导致waiting状态,线程锁住导致blocked状态),调用interrupt,将会抛出InterruptedException,并将状态改为非中断状态,线程并不中止,代码还是会继续执行。
在上文main方法中将stopThread.stop()改为stopThread.interrupt();输出结果将会变为i=1,j=1,并抛出InterruptedException
2、如果线程正常执行,调用interrupt,它只会改变线程的中断状态,线程并不中止,代码继续执行。
ps:调用interrupted()在获取到线程状态的同时,会重置线程的中断状态为非中断;调用isInterrupted()则只会获取线程状态,不会进行重置操作
public static void main(String[] args) throws InterruptedException {
InterruptThread interruptThread = new InterruptThread();
interruptThread.start();
Thread.sleep(1);
interruptThread.interrupt();
System.out.println("main线程");
}
static class InterruptThread extends Thread {
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted状态");
//如果不手动return,线程会一直执行打印:“Interrupted状态”
return;
} else {
System.out.println("unInterrupted状态");
}
}
}
}
上面的代码,如果不自行在判断中加入中止操作,线程并不中止,会持续打印:“Interrupted状态”。
通过状态位来中止线程
手动设置状态变量,根据状态位来判断,是否中止线程。
PS:注意状态变量的可见性
//注意使用volatile 保证变量的可见性
public static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (flag) {
System.out.println("线程执行中!");
}
});
thread.start();
Thread.sleep(1);
flag = false;
while (thread.isAlive()) {
}
System.out.println("程序运行结束!");
}
通过状态位可以比较优雅的中止线程,但如果碰到线程挂起,只通过状态位判断来处理是不能解决的,这时可以结合interrupt来中断被挂起的线程。
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (flag) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
System.out.println("退出waiting状态!");
}
System.out.println("线程执行中!");
}
});
thread.start();
Thread.sleep(1);
flag = false;
Thread.sleep(1000);
thread.interrupt();
while (thread.isAlive()) {
}
System.out.println("程序运行结束!");
}
线程通信
多个线程并发执行时, 在默认情况下CPU是随机切换线程的,当我们需要多个线程来共同完成一件任务,并且我们希望他们有规律的执行, 那么多线程之间需要一些协调通信,以此来帮我们达到多线程共同操作一份数据。
下面是三种线程协作通信方式的对比:suspend/resume、wait/notify、park/unpark。
suspend/resume
suspend在调用时并不会释放锁资源,同时suspend/resume对执行的顺序有严格的要求。这两点都非常容易导致代码死锁,所以官方不建议通过suspend/resume的方式来进行通信,挂起和唤醒线程。
//suspend未释放锁导致代码死锁
public static volatile boolean flag = true;
public static void main(String[] args) throws Exception {
new Demo().SuspendThread();
System.out.println("程序运行结束!");
}
public void SuspendThread () {
Thread thread = new Thread(()->{
synchronized (this) {
System.out.println("线程运行中!");
while (flag) {
System.out.println("执行suspend!");
Thread.currentThread().suspend();
}
}
});
System.out.println("线程start!");
thread.start();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
synchronized (this) {
System.out.println("执行resume!");
thread.resume();
}
thread.join();
}
//resume先于suspend执行,导致死锁
public void SuspendThread () throws InterruptedException {
Thread thread = new Thread(()->{
while (flag) {
System.out.println("线程睡眠3秒!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行suspend!");
Thread.currentThread().suspend();
}
});
System.out.println("线程start!");
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
System.out.println("执行resume!");
thread.resume();
thread.join();
}
wait/notify
wait在调用时会释放掉锁,避免了因未释放锁导致的死锁。但wait/notify对执行顺序有严格的要求,如果notify先于wait执行,还是会导致死锁。
wait/notify的API是由锁对象来调用的,如果调用者不是锁对象,会抛出IllegalMonitorStateException
//notify先于wait执行,导致死锁
public void SuspendThread () throws InterruptedException {
Thread thread = new Thread(()->{
while (flag) {
System.out.println("线程睡眠3秒!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
System.out.println("执行wait!");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
System.out.println("线程start!");
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
System.out.println("执行notifyAll!");
synchronized (this) {
this.notifyAll();
}
thread.join();
}
park/unpark
park/unpark对执行顺序没有要求,但是park并不会释放锁资源,会因为未释放锁而导致的死锁。
//park未释放锁资源,导致死锁
public void SuspendThread () throws InterruptedException {
Thread thread = new Thread(()->{
synchronized (this) {
System.out.println("线程运行中!");
while (flag) {
System.out.println("执行park()!");
LockSupport.park();
}
}
});
System.out.println("线程start!");
thread.start();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
synchronized (this) {
System.out.println("执行unpark()");
LockSupport.unpark(thread);
}
thread.join();
}
线程封闭
在Java内存模型中,Java虚拟机栈、本地方法栈、程序计数器都是属于线程独享的内存区域。因此存储于虚拟机栈空间中的局部变量天然就具有线程封闭的特性。
除开线程独享区域的变量,如果我们想要让线程独享某些变量,那么我们还可以使用ThreadLocal让变量达到线程封闭的效果。
public static ThreadLocal<String> value = new ThreadLocal<>();
public static void main(String[] args) throws Exception {
value.set("这是main函数设置的变量!");
Thread thread1 = new Thread(() -> {
System.out.println("thread1获取的变量值为:"+value.get());
});
thread1.start();
System.out.println("main函数的ThreadLocal变量为:"+value.get());
}