Hi,
I am having a question about the SynchronizedExample1 lab. If I am
not using the static method to do the print, instead, I have a
PrintTwoString print method(), the output does not look correct even
this print method is synchronized. Can you help me to understand why
this is the case? If I use the static method, then this code is
synchronized, and the output looks correct. Thanks!
The following is the output:
A C E B
F
D
Code:
public class SyncThreadExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SyncThreadExampleHelper sth1 = new SyncThreadExampleHelper("A",
"B");
SyncThreadExampleHelper sth2 = new SyncThreadExampleHelper("C",
"D");
SyncThreadExampleHelper sth3 = new SyncThreadExampleHelper("E",
"F");
//sth1.print();
}
}
public class SyncThreadExampleHelper extends Thread {
private String firstName;
private String lastName;
public SyncThreadExampleHelper(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
start();
}
public void run()
{
//PTW.print(firstName, lastName);
PrintTwoString ptws = new PrintTwoString(firstName, lastName);
ptws.print();
}
}
public class PrintTwoString {
PrintTwoString(String a, String b)
{
this.a = a;
this.b = b;
}
synchronized void print()
{
System.out.print(a + " " );
try
{
Thread.sleep((long)(Math.random() * 1000));
}
catch(InterruptedException ie)
{
}
System.out.println(b);
}
private String a;
private String b;
}
Lawrence Louie
--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en