You are on page 1of 14

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

Mobilesprogramming's Blog
JAVA | SYMBIAN | ANDROID

Tm hiu Thread trong JAVA Phn 5


Bi 4: ng b ha(Synchronized) Thread (tip theo) 3.Static synchronized method: Ngoi lock cp i tng(object-level) cho mi instance ca lp, cn c lock cp lp (classlevel) c chia s cho tt c instance ca mt lp c th. Mi lp np bi JavaVM c ng mt lock class-level. Nu mt phng thc c khai bo c 2 t kha static v synchronized, mt thread phi c c quyn truy cp vo lock class-level trc khi i vo phng thc. Lock class-level c th c s dng truy cp c quyn vo cc bin thnh vin static. Cng nh lock object-level cn c ngn chn s sa i d liu ca cc bin thnh vin non-static, lock class-level cng cn c ngn chn s sa i ca cc bin thnh vin static. Thm ch l khi khng c bin no lin quan, th modifier synchronized cng c th c s dng trn cc phng thc static nhm m bo ch c mt thread nm bn trong mt phng thc ti mt thi im. hiu r thm v vn ny, ta xt v d sau: 1: public class StaticNeedSync extends Object { 2: 3: 4: 5: 6: 7: 8: 9: // Simulate a delay that is possible if the thread // scheduler chooses to swap this thread off the // processor at this point. The delay is exaggerated
1/14

private static int nextSerialNum = 10001;

public static int getNextSerialNum() { int sn = nextSerialNum;

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: } }

// for demonstration purposes. try { Thread.sleep(1000); } catch ( InterruptedException x ) { }

nextSerialNum++; return sn;

private static void print(String msg) { String threadName = Thread.currentThread().getName(); System.out.println(threadName + : + msg);

public static void main(String[] args) { try { Runnable r = new Runnable() { public void run() { print(getNextSerialNum()= + getNextSerialNum()); } };

Thread threadA = new Thread(r, threadA); threadA.start();

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

2/14

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: } } }

Thread.sleep(1500);

Thread threadB = new Thread(r, threadB); threadB.start();

Thread.sleep(500);

Thread threadC = new Thread(r, threadC); threadC.start();

Thread.sleep(2500);

Thread threadD = new Thread(r, threadD); threadD.start(); } catch ( InterruptedException x ) { // ignore

Lp StaticNeedSync c mt bin thnh vin nextSerialNum vi khai bo private static, c dng lu gi tr cc s tip theo s c to ra (dng 2). Phng thc getNextSerialNum () (dng 416) l c khai bo public v static. Khi gi phng thc ny, n c gi tr hin ti ca nextSerialNum v lu tr n trong mt bin cc b sn (dng 5). Sau , thread gi phng thc ny tm sleep 1 giy(dng 11) mt thread th 2 thc hin. Khi cc thread nhn c mt c hi chy li, n tng nextSerialNum ln 1 bin chun b cho cuc gi tip theo (dng 14). Main thread c 4 thread tng tc vi phng thc getNextSerialNum(). C 4 thread u s dng cng mt i tng Runnable(dng 25-30). Main thread bt u vi threadA(dng 33) v sleep khong 1,5 giy. Thi gian ny threadA vo v tr v t phng thc getNextSerialNum(). Tip theo, main Thread tip tc bt u vi threadB(dng 38), sau n sleep khong 0,5 giy(dng
https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/ 3/14

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

40) trc khi n bt u threadC(dng 43). C threadB v threadC cng nm trong phng thc getNextSerialNum(), v iu ny lm ny sinh mt vi vn . Sau khi ch 2,5 giy (nhiu thi gian cho threadB v threadC tr v), main thread bt u threadD (dng 45-48). threadD gi phng thc getNextSerialNum () ln cui cng. Kt qu di y m t v d trn: threadA: getNextSerialNum()=10001 threadB: getNextSerialNum()=10002 threadC: getNextSerialNum()=10002 threadD: getNextSerialNum()=10004 gii quyt vn trn, ta ch cn thm vo t kha synchronized vo phng thc getNextSerialNum(). 1: public class StaticSync extends Object { 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17:
https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/ 4/14

private static int nextSerialNum = 10001;

public static synchronized int getNextSerialNum() { int sn = nextSerialNum;

// Simulate a delay that is possible if the thread // scheduler chooses to swap this thread off the // processor at this point. The delay is exaggerated // for demonstration purposes. try { Thread.sleep(1000); } catch ( InterruptedException x ) { }

nextSerialNum++; return sn; }

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42:

private static void print(String msg) { String threadName = Thread.currentThread().getName(); System.out.println(threadName + : + msg); }

public static void main(String[] args) { try { Runnable r = new Runnable() { public void run() { print(getNextSerialNum()= + getNextSerialNum()); } };

Thread threadA = new Thread(r, threadA); threadA.start();

Thread.sleep(1500);

Thread threadB = new Thread(r, threadB); threadB.start();

Thread.sleep(500);

Thread threadC = new Thread(r, threadC);


5/14

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: } } }

threadC.start();

Thread.sleep(2500);

Thread threadD = new Thread(r, threadD); threadD.start(); } catch ( InterruptedException x ) { // ignore

Kt qu t v d trn: threadA: getNextSerialNum()=10001 threadB: getNextSerialNum()=10002 threadC: getNextSerialNum()=10003 threadD: getNextSerialNum()=10004 S d vn trn c gii quyt l do khi threadC vo phng thc getNextSerialNum(), n lp tc ri vo trng thi block v i threadB kt thc n mi c php tip tc thc hin trong phng thc getNextSerialNum(). 4.S dng Class-level lock trong synchronized statement. s dng synchronized statement trong Class-level lock, ta s dng theo c php sau: synchronized ( ClassName.class ) { // body } V d: ta to lp StaticBlock m phng k thut trn nh sau: 1: public class StaticBlock extends Object {
https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/ 6/14

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26:

public static synchronized void staticA() { System.out.println(entering staticA());

try { Thread.sleep(5000); } catch ( InterruptedException x ) { }

System.out.println(leaving staticA()); }

public static void staticB() { System.out.println(entering staticB());

synchronized ( StaticBlock.class ) { System.out.println( in staticB() inside sync block);

try { Thread.sleep(2000); } catch ( InterruptedException x ) { } }

System.out.println(leaving staticB()); }

public static void main(String[] args) { Runnable runA = new Runnable() {


7/14

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: } } }; };

public void run() { StaticBlock.staticA(); }

Thread threadA = new Thread(runA, threadA); threadA.start();

try { Thread.sleep(200); } catch ( InterruptedException x ) { }

Runnable runB = new Runnable() { public void run() { StaticBlock.staticB(); }

Thread threadB = new Thread(runB, threadB); threadB.start();

Trong lp StaticBlock, phng thc staticA() c khai bo synchronized v static. Phng thc staticB() c khai bo static v c cha mt block synchronized(dng 14-20). Cc i tng s dng kim sot truy cp vo block ny l i tng Class cho StaticBlock v c tm thy bng cch s StaticBlock.class(dng 14). Trong phng thc main, threadA c bt u v gi phng thc staticA()(dng 28). Sau mt khong thi gian 200 mili giy, threadB bt u v gi phng thc staticB(). Trong khi threadA sleep trong phng thc staticA(), threadB vo phng thc staticB(), in mt message v i vo
https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/ 8/14

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

block static synchronized(dng 14). Khi threadA tr v t staticA(), threadB nhn class-level lock v hon tt phng thc staticB(). Sau y l kt qu ca v d trn: 1: entering staticA() 2: entering staticB() 3: leaving staticA() 4: in staticB() inside sync block 5: leaving staticB() Lu rng, mc d threadB c th vo phng thc staticB()(dng 2) nhng n khng th vo thc hin block synchronized(dng 4) cho n khi threadA tr v t staticA()(dng 3). ThreadB s ri vo trng thi block cho ti khi threadA gii phng class-level lock. 5.Deadlocks: Khi s dng nhiu thread truy cp vo cc i tng c gi lock, nu khng cn thn th rt c th xy ra tnh trng deadlocks. l khi mt threadA nm gi lock1, mt threadB nm gi lock2. Trong khi threadA nm gi lock1, n li mun nm gi thm lock2, nhng v threadB ang nm gi lock2 nn threadA s ri vo trng thi block, v n phi i cho ti khi threadB gii phng lock2. Tuy nhin, vo thi im , trong khi threadB ang nm gi lock2, n li mun tip tc nm gi lock1, v lock1 ang c nm gi bi threadA, nn threadB li ri vo trng thi block. Lc ny, c threadA v threadB ri vo trng thi block mi mi v phi i thread kia gii phng lock. y chnh l trng hp deadlocks. V d: 1: public class Deadlock extends Object { 2: 3: 4: 5: 6: 7: 8: public synchronized void checkOther(Deadlock other) {
9/14

private String objID;

public Deadlock(String id) { objID = id; }

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: } }

print(entering checkOther());

// simulate some lengthy process try { Thread.sleep(2000); } catch ( InterruptedException x ) { }

print(in checkOther() about to + invoke other.action()); other.action();

print(leaving checkOther());

public synchronized void action() { print(entering action());

// simulate some work here try { Thread.sleep(500); } catch ( InterruptedException x ) { }

print(leaving action());

public void print(String msg) { threadPrint(objID= + objID + + msg);


10/14

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58:

public static void threadPrint(String msg) { String threadName = Thread.currentThread().getName(); System.out.println(threadName + : + msg); }

public static void main(String[] args) { final Deadlock obj1 = new Deadlock(obj1); final Deadlock obj2 = new Deadlock(obj2);

Runnable runA = new Runnable() { public void run() { obj1.checkOther(obj2); } };

Thread threadA = new Thread(runA, threadA); threadA.start();

try { Thread.sleep(200); } catch ( InterruptedException x ) { }

Runnable runB = new Runnable() { public void run() {


11/14

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: }; }

obj2.checkOther(obj1);

Thread threadB = new Thread(runB, threadB); threadB.start();

try { Thread.sleep(5000); } catch ( InterruptedException x ) { }

threadPrint(finished sleeping);

threadPrint(about to interrupt() threadA); threadA.interrupt();

try { Thread.sleep(1000); } catch ( InterruptedException x ) { }

threadPrint(about to interrupt() threadB); threadB.interrupt();

try { Thread.sleep(1000); } catch ( InterruptedException x ) { }

threadPrint(did that break the deadlock?);


12/14

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

84: 85: }

Trong phng thc main(), c hai instance ca Deadlock c to ra v hai thread c bt u, mi thread chy trn mt instance; instance th nht c thit lp l obj1, ci kia l obj2(dng 4243). ThreadA c start v gi phng thc checkOther() ca obj1 v gn mt tham chiu n obj2(dng 47), sau khi sleep khong 200 mili giy, threadB c start v gi phng thc checkOther() ca obj2 v n gn mt tham chiu ti obj1. Phng thc checkOther() l synchronized nn thread truy cp vo n s nhn lock. C threadA v threadB s khng bao gi thc hin c phng thc action(), v khi threadA ang trong phng thc checkOther() n nm gi lock trn obj1, th threadB cng trong phng thc checkOther() v nm gi lock ca obj2. Khi threadA c gng gi phng thc action() trong obj2, n s b block do threadB ang nm gi lock trn obj2, v n s i cho ti khi threadB gii phng lock trn obj2. Sau , threadB gi phng thc action() trn obj1 v cng ri vo trng thi block do lock trn obj1 b threadA chim gi; main thread sleep trong 5 giy khi deadlock c to ra(dng 66), khi tnh dy, n c gng ph v deadlock bng cch interrupt threadA(dng 72), sau 1 giy n tip tc c gng interrupt threadB. Tht khng may, iu ny khng ph v deadlock, bi khi mt thread ang b block v i c c lock, n khng p ng vi interrupt. Kt qu t v d trn: threadA: objID=obj1 entering checkOther() threadB: objID=obj2 entering checkOther() threadA: objID=obj1 in checkOther() about to invoke other.action() threadB: objID=obj2 in checkOther() about to invoke other.action() main: finished sleeping main: about to interrupt() threadA main: about to interrupt() threadB main: did that break the deadlock? Bn thy bi vit ny th no? Cc bi lin quan: Tm hiu Thread trong Java Phn 4 08/12/2010 mobilesprogramming Categories: Thread Tags: java thread

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

13/14

19/07/2012

Tm hiu Thread trong JAVA Phn 5 Mobilesprogramming's Blog

3 responses to Tm hiu Thread trong JAVA Phn 5


Huang August 23rd, 2010 at 22:17 gii quyt vn khi m trng hp deadlock xy ra phi lm th no bn i? Reply mobilesprogramming August 24th, 2010 at 14:18 Cho bn! C rt nhiu cch hn ch tnh trng Deadlock, tuy nhin c 2 cch thng hay s dng: - Nm gi lock ca i tng trong thi gian cng t cng tt, cch ny thng s dng synchronized statement block thay th cho sychronized method. - Thit k h thng sao cho khng nm gi nhiu hn mt lock ti mt thi im. Trong v d trn, dng 17, nu bn thay th bng: this.action(); th s hn ch c tnh trng Deadlock. Reply Gin April 19th, 2011 at 17:03 Thanks so much! The articles are very helpful and helped me a lot. I hope you will write more in the future. Thanks again ! Reply

Blog at WordPress.com. | Theme: Dark Wood by Nischal Maniar.

https://mobilesprogramming.wordpress.com/2010/08/12/tim-hiu-thread-trong-java-phn-5/

14/14

You might also like