Saturday, September 4, 2010

Java SynDemo object to solve the problem of succession

Java SynDemo object has just appeared in time to have a lot of programmers are headache, this is actually not necessary, and here's the Xuexi in detail under the related issues. We found that, for the Java SynDemo objects, only synMethord1 run, while synMethord2 is not running. This is to be synchronized in the method-level statement of the l. ..

Java SynDemo object appeared just when many programmers are headache, this is actually not necessary, here we come to study in detail under the relevant issues. We found that, for the Java SynDemo objects, only synMethord1 run, while synMethord2 is not running. This is to be synchronized in the method-level statement will lock the current instance of this class object. So synMethord1 unlock before running the end of the current Java SynDemo object instance is not run synMethord2's. This method-level synchronized statement and the following approach is equivalent to:

1.package com.cnblogs.gpcuster; / ** * * @ author Aaron.Guo * * /
2.public class SynDemo (public void synMethord1 () (
synchronized (this) (while (true) (try (Thread.sleep (1000);
System.out.println ("synMethord1");) catch (InterruptedException
e) (/ / TODO Auto-generated catch block
3.e.printStackTrace ();
4.)
5.)
6.)
7.)
8.public void synMethord2 () (synchronized (this) (while (true)
(Try (Thread.sleep (1000); System.out.println ("synMethord2");)
catch (InterruptedException e) (/ / TODO Auto-generated catch block
9.e.printStackTrace ();
10.)
11.)
12.)
13.)
14.)
Run the program, results and last the same.
If we wish to synchronize two methods are how to deal with? Can refer to this realization:
15.package com.cnblogs.gpcuster; / ** * * @ author Aaron.Guo * * /
16.public class SynDemo (private Object flag1 = new Object ();
private Object flag2 = new Object (); public void synMethord1 ()
(Synchronized (flag1) (while (true) (try (Thread.sleep (1000);
System.out.println ("synMethord1");) catch (Interrupted
Exception e) (/ / TODO Auto-generated catch block
17.e.printStackTrace ();
18.)
19.)
20.)
21.)
22.public void synMethord2 () (synchronized (flag2) (while (true)
(Try (Thread.sleep (1000); System.out.println ("synMethord2");)
catch (InterruptedException e) (/ / TODO Auto-generated catch block
23.e.printStackTrace ();
24.)
25.)
26.)
27.)
28.)
Run the program, the results as we expect:
29.main
30.synMethord2
31.synMethord2
32.main
33.synMethord1
34.main
35.synMethord1
36.synMethord2
About Synchronized There were some other topics, such as the static problem, the question of succession, and with use of so volatile, the Internet has a very detailed description will not repeat here introduced. Is on the Java SynDemo more details about the object.

No comments:

Post a Comment