1.yield()/sleep()/join() java.lang.Thread
join方法等待线程运行结束
sleep方法使线程阻塞一定的时间
yield方法使线程放弃一次调度机会
2.wait()/notifyAll()/notify() java.lang.Object
wait方法使线程阻塞直至其它线程调用notify或notifAll
notifyAll方法唤醒所有等在对象锁的线程
notify方法唤醒一个等在对象锁的线程
3.sleep() 与 wait()
两者都使线程阻塞,但sleep时当前线程不释放对象锁,wait时则释放对象锁
4.中断
java.lang.Thread:
void interrupt(),改变中断状态
static boolean interrupted(),检查并清除中断状态
boolean isInterrupted(),检查中断状态
Object.wait、Thread.sleep、Thread.join这些方法内部会不断检查中断状态的值,并抛出InterruptedException异常
//
java.lang.Object
每个对象有两个线程等待队列,一个是activeQueue,一个是passiveQueue
//**************************************
synchronized{ //get the monitor or added to activeQueue
} //release the monitor and choose one in activeQueue
wait
1.release monitor
2.added to passiveQueue(wait for notify/notifyAll)
3.added to activeQueue
notify/notifyAll
move one or all of passiveQueue to activeQueue
//**************************************
在调用wait时,若产生中断,仅仅是把线程从passiveQueue移到activeQueue,保证在任何情况下,synchronized块内的语句都有monitor
//
5.synchronized(m)使用
synchronized(m){
}
相当于
//#1
Lock(m)//申请互斥变量m
//#2
UnLock(m)//释放互斥变量m
//#3
四种方式:
5.IllegalMonitorStateException
当一个线程并不拥有一个对象的互斥锁时,如果调用wait/notifyAll/notify就会产生这个异常。
6.用pthread API模拟synchronized wait notify/notifyAll
synchronized(obj){ ——》pthread_mutex_lock(obj.mutex)
} ——》pthread_mutex_unlock(obj.mutex)
obj.wait() ——》pthread_cond_wait(obj.cond,obj.mutex.);
obj.notify() ——》pthread_cond_signal(obj.cond)
obj.notifyAll ——》pthread_cond_broadcast(obj.cond)
pthread_cond_wait(c,m)做了以下三件事
1.释放互斥锁m
2.获取条件变量c
3.获取互斥锁m