线ç¨çç¶æ转æ¢æ¯çº¿ç¨æ§å¶çåºç¡ã线ç¨ç¶ææ»çå¯å为äºå¤§ç¶æï¼åå«æ¯çãæ»ãå¯è¿è¡ãè¿è¡ãçå¾ /é»å¡ãç¨ä¸ä¸ªå¾æ¥æè¿°å¦ä¸ï¼
1ãæ°ç¶æï¼çº¿ç¨å¯¹è±¡å·²ç»å建ï¼è¿æ²¡æå¨å ¶ä¸è°ç¨start()æ¹æ³ã
2ãå¯è¿è¡ç¶æï¼å½çº¿ç¨æèµæ ¼è¿è¡ï¼ä½è°åº¦ç¨åºè¿æ²¡ææå®éå®ä¸ºè¿è¡çº¿ç¨æ¶çº¿ç¨æå¤çç¶æãå½start()æ¹æ³è°ç¨æ¶ï¼çº¿ç¨é¦å è¿å ¥å¯è¿è¡ç¶æãå¨çº¿ç¨è¿è¡ä¹åæè ä»é»å¡ãçå¾ æç¡ç ç¶æåæ¥åï¼ä¹è¿åå°å¯è¿è¡ç¶æã
3ãè¿è¡ç¶æï¼çº¿ç¨è°åº¦ç¨åºä»å¯è¿è¡æ± ä¸éæ©ä¸ä¸ªçº¿ç¨ä½ä¸ºå½å线ç¨æ¶çº¿ç¨æå¤çç¶æãè¿ä¹æ¯çº¿ç¨è¿å ¥è¿è¡ç¶æçå¯ä¸ä¸ç§æ¹å¼ã
4ãçå¾ /é»å¡/ç¡ç ç¶æï¼è¿æ¯çº¿ç¨æèµæ ¼è¿è¡æ¶å®æå¤çç¶æãå®é ä¸è¿ä¸ªä¸ç¶æç»å为ä¸ç§ï¼å ¶å ±åç¹æ¯ï¼çº¿ç¨ä»æ§æ¯æ´»çï¼ä½æ¯å½å没ææ¡ä»¶è¿è¡ãæ¢å¥è¯è¯´ï¼å®æ¯å¯è¿è¡çï¼ä½æ¯å¦ææ件äºä»¶åºç°ï¼ä»å¯è½è¿åå°å¯è¿è¡ç¶æã
5ãæ»äº¡æï¼å½çº¿ç¨çrun()æ¹æ³å®ææ¶å°±è®¤ä¸ºå®æ»å»ãè¿ä¸ªçº¿ç¨å¯¹è±¡ä¹è®¸æ¯æ´»çï¼ä½æ¯ï¼å®å·²ç»ä¸æ¯ä¸ä¸ªåç¬æ§è¡ç线ç¨ã线ç¨ä¸æ¦æ»äº¡ï¼å°±ä¸è½å¤çã å¦æå¨ä¸ä¸ªæ»å»ç线ç¨ä¸è°ç¨start()æ¹æ³ï¼ä¼æåºjava.lang.IllegalThreadStateExceptionå¼å¸¸ã
æå ³è¯¦ç»ç¶æ转æ¢å¾å¯ä»¥åçæ¬äººçâJavaå¤çº¿ç¨ç¼ç¨æ»ç»âä¸çå¾
äºãé»æ¢çº¿ç¨æ§è¡
对äºçº¿ç¨çé»æ¢ï¼èèä¸ä¸ä¸ä¸ªæ¹é¢ï¼ä¸èèIOé»å¡çæ åµï¼
ç¡ç ï¼
çå¾ ï¼
å 为éè¦ä¸ä¸ªå¯¹è±¡çéå®è被é»å¡ã
1ãç¡ç
Thread.sleep(long millis)åThread.sleep(long millis, int nanos)éææ¹æ³å¼ºå¶å½åæ£å¨æ§è¡ç线ç¨ä¼ç ï¼æåæ§è¡ï¼ï¼ä»¥âåæ ¢çº¿ç¨âãå½çº¿ç¨ç¡ç æ¶ï¼å®å ¥ç¡å¨æ个å°æ¹ï¼å¨èéä¹åä¸ä¼è¿åå°å¯è¿è¡ç¶æãå½ç¡ç æ¶é´å°æï¼åè¿åå°å¯è¿è¡ç¶æã
线ç¨ç¡ç çåå ï¼çº¿ç¨æ§è¡å¤ªå¿«ï¼æè éè¦å¼ºå¶è¿å ¥ä¸ä¸è½®ï¼å 为Javaè§èä¸ä¿è¯åççè½®æ¢ã
ç¡ç çå®ç°ï¼è°ç¨éææ¹æ³ã
try {
Thread.sleep(123);
} catch (InterruptedException e) {
e.printStackTrace();
}
ç¡ç çä½ç½®ï¼ä¸ºäºè®©å ¶ä»çº¿ç¨ææºä¼æ§è¡ï¼å¯ä»¥å°Thread.sleep()çè°ç¨æ¾çº¿ç¨run()ä¹å ãè¿æ ·æè½ä¿è¯è¯¥çº¿ç¨æ§è¡è¿ç¨ä¸ä¼ç¡ç ã
ä¾å¦ï¼å¨åé¢çä¾åä¸ï¼å°ä¸ä¸ªèæ¶çæä½æ¹ä¸ºç¡ç ï¼ä»¥åæ ¢çº¿ç¨çæ§è¡ãå¯ä»¥è¿ä¹åï¼
public void run() {
for(int i = 0;i<5;i++){
// å¾èæ¶çæä½ï¼ç¨æ¥åæ
¢çº¿ç¨çæ§è¡
// for(long k= 0; k <100000000;k++);
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace(); .
}
System.out.println(this.getName()+" :"+i);
}
}