java 多线程等待与唤醒机制

时间:2022-03-17 14:33:05

java 并发编程网站 :http://ifeve.com/java-7-concurrency-cookbook/

一:

1:JVM线程状态

NEWRUNNABLEBLOCKEDWAITINGTIMED_WAITINGTERMINATED

BLOCKED是等待获得对象锁

WAITING是调用了wait, sleep, park

2:

sleep, 进入TIMED_WAITING状态,不出让锁

wait, 进入TIMED_WAITING状态,出让锁,并进入对象的等待队列

park, 进入WAITING状态,对比wait不需要获得锁就可以让线程WAITING,通过unpark唤醒

interrupt, 只是给线程发个信号,如果在wait, sleep会收到exception

yeild, 在操作系统层面让线程从running变成ready状态,等待继续被调度。在jvm的线程状态还是RUNNABLE

二:代码实现

package com.tc;


import java.util.concurrent.locks.LockSupport;


public class ThreadPark {


public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mt.park();
System.out.println("canyou get here?");
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mt.unPark();


}

static class MyThread extends Thread {

private boolean isPark = false;


public void run() {
while (true) {
if (isPark)
LockSupport.park();
System.out.println("running....");
}
}


public void park() {
isPark = true;
}


public void unPark() {
isPark = false;
LockSupport.unpark(this);
}


}
}