Ò׽ؽØͼÈí¼þ¡¢µ¥Îļþ¡¢Ãâ°²×°¡¢´¿ÂÌÉ«¡¢½ö160KB

java Ïß³ÌС½á

1, ΪʲôwaitÓënotify֮ǰ±ØÐëÒª¼Ósynchronized?
´ð°¸ÆäʵºÜ¼òµ¥£¬Ò²ÊÇΪÁË·ÀÖ¹µÈ´ý-֪ͨ»úÖƳöÏÖrace condition
Ϊʲô»á³öÏÖrace condition ?
´ð£º ¶ÔÏóÔÚ±»wait֮ǰÒѾ­±»ÁíÒ»Ïß³Ìnotify , Ö®ºóµÄwait »áÓÀ¾ÃÍ£Ö¹,²¢µ¼ÖÂdeadlock(ËÀËø)
ÀíÏëÇé¿ö£º
1, µÚÒ»¸öÏß³ÌÅжϸöÔÏóÊÇ·ñÒªwait
2, µÚÒ»¸öÏ߳̽«¶ÔÏówait
3, µÚ¶þ¸öÏß³ÌÔÙ½«¶ÔÏónotify
ʵ¼ÊÇé¿ö
1, µÚÒ»¸öÏß³ÌÅжϸöÔÏóÊÇ·ñÒªwait
2, µÚ¶þ¸öÏ߳̽«¶ÔÏónotify
3, µÚÒ»¸öÏ߳̽«¶ÔÏówait
ΪÁË·ÀÖ¹ÕâЩÇé¿ö£¬²ÅÐèÒªÔÚwaitÓënotify֮ǰ¼Ósynchronized
java ´úÂë
A a = A.getInstance();//µ¥Àý¶ÔÏó,ͬһ·ÝʵÀý²»Ïú»Ù
synchronized (a) {
a.wait();
}
-------------------------------ÁíÒ»Ïß³Ì
A a = A.getInstance();
synchronized(a) {
a.notify();
}
µÈ´ý-֪ͨ»úÖƱØÐëÓësychronizedÒ»ÆðÓÃ,·ñÔò×ÔÉíÒ²»áÓÐ race condition.
2, ¾²Ì¬Í¬²½·½·¨Óë·Ç¾²Ì¬Í¬²½·½·¨µÄÇø±ð
ÓÐʱ£¬ÎÒÃǾ­³£»áÅöµ½ÕâÑùµÄ´úÂ룡
ÒµÎñÂß¼­µÄ·â×°Àà:
public class Logic {
private static final Log log = LogFactory.getLog(Logic.class);
private static Logic logic;
 
private Logic() {}
 
public static Logic getInstance() {
if (null == logic) {
logic = new Logic();
}
 
return logic;
}
 
public static synchronized void testStatic() {
log.info(Thread.currentThread().getName() + " : static method is running");
}
 
public synchronized void testNonStatic() {
log.info(Thread.currentThread().getName() + " : non static method is running");
}
}
·Ç¾²Ì¬·½·¨µÄÖ´ÐÐ:
public class ThreadRun1 extends Thread {
private static final Log log = LogFactory.getLog(ThreadRun1.class);
 
public void run() {
Logic logic = Logic.getInstance(); // object reference
 
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
log.error("some exceptions occured :", e);
}
 
logic.testNonStatic();
 
logEnd();
}
 
private void logEnd() {
log.info("thread ru


Ïà¹ØÎĵµ£º

Java²Ù×÷ÎļþʵÀýÏê½âÓ¦ÓÃ

ÊäÈëÊä³öÁ÷
ÔÚJavaÖУ¬ÎÒÃÇ°ÑÄܹ»¶ÁÈ¡Ò»¸ö×Ö½ÚÐòÁеĶÔÏó³Æ×÷Ò»¸öÊäÈëÁ÷;¶øÎÒÃǰѹ»Ð´Ò»¸ö×Ö½ÚÐòÁгÆ×÷Ò»¸öÊä³öÁ÷¡£ËüÃÇ·Ö±ðÓɳéÏóÀà InputStreamºÍOutputStreamÀà±íʾ¡£ÒòΪÃæÏò×Ö½ÚµÄÁ÷²»·½±ãÓÃÀ´´¦Àí´æ´¢ÎªUnicode£¨Ã¿¸ö×Ö·ûʹÓÃÁ½¸ö×Ö½Ú)µÄÐÅÏ¢¡£ËùÒÔJavaÒýÈëÁËÓÃÀ´´¦ÀíUnicode×Ö·ûµÄÀà²ã´Î£¬ÕâЩÀàÅÉÉú×Ô³éÏóÀàReade ......

java ÖÐµÄ synchronized

synchronized£º ͬ²½µÄ
synchronizedÔÚ²Ù×÷ÉÏÓÐÁ½ÖÖÓ°Ïì¶ÔÏóµÄÇé¿ö£º
1) ÔÚij¸ö¶ÔÏóʵÀýÄÚ£¬synchronized method(){}¿ÉÒÔ·ÀÖ¹¶à¸öÏß³Ìͬʱ·ÃÎÊÕâ¸ö¶ÔÏóµÄsynchronized·½·¨£¨Èç¹ûÒ»¸ö¶ÔÏóÓжà¸ösynchronized·½·¨£¬Ö»ÒªÒ»¸öÏ̷߳ÃÎÊÁËÆäÖеÄÒ»¸ösynchronized·½·¨£¬ÆäËüÏ̲߳»ÄÜͬʱ·ÃÎÊÕâ¸ö¶ÔÏóÖÐÈκÎÒ»¸ösynchronized·½·¨£ ......

javaµÝ¹éÉú³ÉÏÂÀ­Áбí¿ò

½ñÌìÓöµ½Ò»¸öÒªÉú³ÉÒ»¸öÏÂÀ­Áбí¿òµÄÎÊÌ⣬ÎÒµÄÏë·¨ÊÇ£º½«Êý¾Ý¿âÄÚµÄËùÓÐÊý¾Ý¶¼´æ´¢µ½Ò»¸öListÀïÃ棬ÔÙÔÚǰ̨±éÀúÕû¸ölist¡£
Ö´ÐÐЧ¹ûͼ£º
Ë®¹û
→Æ»¹û
→→Æ»¹ûϵÁÐ1
→→Æ»¹ûϵÁÐ2
→→Æ»¹ûϵÁÐ3
→→Æ»¹ûϵÁÐ4
→Àæ
→ÌÒ×Ó
ѧϰÓÃÆ·
→±Ê
→→Ǧ±Ê ......
© 2009 ej38.com All Rights Reserved. ¹ØÓÚE½¡ÍøÁªÏµÎÒÃÇ | Õ¾µãµØͼ | ¸ÓICP±¸09004571ºÅ