线程:等待/通知机制
? 方法wait()
? ?方法wait()的作用是使當(dāng)前執(zhí)行代碼的線程進(jìn)行等待, wait()被執(zhí)行后,鎖被自動(dòng)釋放。wait()方法是Object類的方法,該方法用來將當(dāng)前線程置入"預(yù)執(zhí)行隊(duì)列"中,并且在wait()所在的代碼處停止執(zhí)行,直到接到通知或被中斷為止。
? ?方法notify()
? ?在執(zhí)行完notify()方法后,當(dāng)前線程不會(huì)馬上釋放該對(duì)象鎖,呈wait狀態(tài)的線程也并不能馬上獲取該對(duì)象鎖,要等到執(zhí)行notify()方法的線程將程序執(zhí)行完,也就是退出synchronized代碼塊后,當(dāng)前線程才會(huì)釋放鎖,而呈wait狀態(tài)所在的線程才可以獲取該對(duì)象鎖。
? ?notify()方法一次只隨機(jī)通知一個(gè)線程進(jìn)行喚醒。
? ?notifyAll()方法喚醒所有線程。
wait(long)方法
? ?帶一個(gè)參數(shù)的wait(long)方法的功能是等待某一時(shí)間是否有線程對(duì)鎖進(jìn)行喚醒,如果超過這個(gè)時(shí)間則自動(dòng)喚醒。
public class Run {static private Object lock = new Object();static private Runnable runable1 = new Runnable(){@Overridepublic void run() {synchronized(lock){try {System.out.println("wait begin timer" + System.currentTimeMillis());lock.wait(5000);System.out.println("wait end timer" + System.currentTimeMillis());} catch (InterruptedException e) {e.printStackTrace();}}}};public static void main(String[] args){Thread t = new Thread(runable1);t.start();} }??
?
當(dāng)interrupt方法遇到wait方法
? 當(dāng)線程呈wait狀態(tài)時(shí), 調(diào)用線程對(duì)象的interrupt()方法會(huì)出現(xiàn)InterruptedException異常.
public class Service {public void testMethod(Object lock){try{synchronized(lock){System.out.println("begin wait...");lock.wait();//Thread.sleep(10000);System.out.println(" end wait...");}}catch(InterruptedException e){e.printStackTrace();System.out.println("出現(xiàn)異常了,因?yàn)槌蕎ait狀態(tài)的線程被interrupt了 !");}} }public class ThreadA extends Thread{private Object lock;public ThreadA(Object lock){this.lock = lock;}@Overridepublic void run(){Service service = new Service();service.testMethod(lock);} }public class Test {public static void main(String[] args){try{Object lock = new Object();ThreadA a = new ThreadA(lock);a.start();Thread.sleep(5000);a.interrupt();}catch(InterruptedException e){e.printStackTrace();}} }通過管道進(jìn)行線程間通信: 字節(jié)流,字符流
? 在jdk中, 提供了4個(gè)類來使線程間可以進(jìn)行通信:?
? ?1). PipedInputStream 和 PipedOutputStream ?處理字節(jié)流
? ?2). PipedReader和PipedWriter ?處理字符流
總結(jié)
以上是生活随笔為你收集整理的线程:等待/通知机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程:volatile关键字
- 下一篇: 线程:方法join的使用