对äºsleep()æ¹æ³ï¼æ们é¦å
è¦ç¥é该æ¹æ³æ¯å±äºThreadç±»ä¸çãèwait()æ¹æ³ï¼åæ¯å±äºObjectç±»ä¸çã
sleep()æ¹æ³å¯¼è´äºç¨åºæåæ§è¡æå®çæ¶é´ï¼è®©åºcpu该å
¶ä»çº¿ç¨ï¼ä½æ¯ä»ççæ§ç¶æä¾ç¶ä¿æè
ï¼å½æå®çæ¶é´å°äºåä¼èªå¨æ¢å¤è¿è¡ç¶æã
å¨è°ç¨sleep()æ¹æ³çè¿ç¨ä¸ï¼çº¿ç¨ä¸ä¼éæ¾å¯¹è±¡éã
èå½è°ç¨wait()æ¹æ³çæ¶åï¼çº¿ç¨ä¼æ¾å¼å¯¹è±¡éï¼è¿å
¥çå¾
æ¤å¯¹è±¡ççå¾
éå®æ± ï¼åªæé对æ¤å¯¹è±¡è°ç¨notify()æ¹æ³åæ¬çº¿ç¨æè¿å
¥å¯¹è±¡éå®æ± åå¤
è·å对象éè¿å
¥è¿è¡ç¶æã
举个åå说æï¼
/**
*
*/
package com.b510.test;
/**
* javaä¸çsleep()åwait()çåºå«
* @author Hongten
* @date 2013-12-10
*/
public class TestD {
public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
private static class Thread1 implements Runnable{
@Override
public void run(){
synchronized (TestD.class) {
System.out.println("enter thread1...");
System.out.println("thread1 is waiting...");
try {
//è°ç¨wait()æ¹æ³ï¼çº¿ç¨ä¼æ¾å¼å¯¹è±¡éï¼è¿å
¥çå¾
æ¤å¯¹è±¡ççå¾
éå®æ±
TestD.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 is going on ....");
System.out.println("thread1 is over!!!");
}
}
}
private static class Thread2 implements Runnable{
@Override
public void run(){
synchronized (TestD.class) {
System.out.println("enter thread2....");
System.out.println("thread2 is sleep....");
//åªæé对æ¤å¯¹è±¡è°ç¨notify()æ¹æ³åæ¬çº¿ç¨æè¿å
¥å¯¹è±¡éå®æ± åå¤è·å对象éè¿å
¥è¿è¡ç¶æã
TestD.class.notify();
//==================
//åºå«
//å¦ææ们æ代ç ï¼TestD.class.notify();ç»æ³¨éæï¼å³TestD.classè°ç¨äºwait()æ¹æ³ï¼ä½æ¯æ²¡æè°ç¨notify()
//æ¹æ³ï¼å线ç¨æ°¸è¿å¤äºæèµ·ç¶æã
try {
//sleep()æ¹æ³å¯¼è´äºç¨åºæåæ§è¡æå®çæ¶é´ï¼è®©åºcpu该å
¶ä»çº¿ç¨ï¼
//ä½æ¯ä»ççæ§ç¶æä¾ç¶ä¿æè
ï¼å½æå®çæ¶é´å°äºåä¼èªå¨æ¢å¤è¿è¡ç¶æã
//å¨è°ç¨sleep()æ¹æ³çè¿ç¨ä¸ï¼çº¿ç¨ä¸ä¼éæ¾å¯¹è±¡éã
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 is going on....");
System.out.println("thread2 is over!!!");
}
}
}
}
è¿è¡ææï¼
enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!
å¦æ注éæ代ç ï¼
TestD.class.notify();
è¿è¡ææï¼
enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!