1.测试代码 如下:
public class TestStringSyn {
private String s1 = new String("abc");
private String s2 = new String("abc");
private String s3 = s1;
private int count = 0;
public void test(){
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
System.out.println("abcd" == "abcd" );
System.out.println("abcd".equals("abcd"));
}
public void test1(){
synchronized (s1) {
count++;
System.out.println("---syn s1-->" + count);
try {
long t1 = (long)Math.random()*1000;
Thread.sleep(100000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void test2(){
synchronized (s2) {
//synchronized (s3) {
count--;
System.out.println("---syn s2-->" + count);
try {
long t1 = (long)Math.random()*1000;
Thread.sleep(t1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void test3(){
synchronized ("abcd") {
count++;
System.out.println("---syn s3-->" + count);
try {
long t1 = (long)Math.random()*1000;
Thread.sleep(100000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void test4(){
synchronized ("abcd") {
count--;
System.out.println("---syn s4-->" + count);
try {
long t1 = (long)Math.random()*1000;
Thread.sleep(t1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
final TestStringSyn tss = new TestStringSyn();
tss.test();
for(int i = 0;i < 10;i++){
new Thread(new Runnable(){
public void run() {
tss.test1();
}
}).start();
}
for(int i = 0;i < 10;i++){
new Thread(new Runnable(){
public void run() {
tss.test2();
}
}).start();
}
// for(int i = 0;i < 10;i++){
// new Thread(new Runnable(){
// public void run() {
// tss.test3();
// }
// }).start();
// }
//
// for(int i = 0;i < 10;i++){
// new Thread(new Runnable(){
// public void run() {
// tss.test4();
// }
// }).start();
// }
}
}
2.测试结果:
a.synchronize(s1) && synchronized(s2) ,结果为s1和s2为不同的锁对象, s1 == s2 为 false
b.synchronize(s1) && synchronized(s3) ,结果为s1和s3为相同的锁对象, s1 == s3 为 true
c.synchronize(“abcd”) && synchronized("abcd"), 结果为相同的锁对象, "abcd" == "abcd" 为true
3.测试结论:
synchronize(String s1) && synchronized(String s2),若s1 == s2 为 true,则为同一锁对象,否则为不同的锁对象。不足之处,请各位补充。