1、多对象同步有两种方法:static synchronized 静态同步方法和synchronized ((""+user_name).intern()) {}字符串锁代码块同步。
2、下面是代码块同步:
package Test;
public class Test {
public static void main(String[] args) throws InterruptedException {
CustomThread uploadDetect1 = new CustomThread();
CustomThread uploadDetect2 = new CustomThread();
CustomThread uploadDetect3 = new CustomThread();
CustomThread uploadDetect4 = new CustomThread();
CustomThread uploadDetect5 = new CustomThread();
Thread t1 = new Thread(uploadDetect1);
Thread t2 = new Thread(uploadDetect2);
Thread t3 = new Thread(uploadDetect3);
Thread t4 = new Thread(uploadDetect4);
Thread t5 = new Thread(uploadDetect5);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Stu1 {
static int count = 100;
public void func(String userId) {
synchronized ((userId).intern()) {
count --;
int out = count;
System.out.println("Count : "+out);
}
}
}
class CustomThread implements Runnable {
Stu1 stu1 = new Stu1();
public void run() {
while(Stu1.count > 0) {
stu1.func("user1");
try {
Thread.sleep(4);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3、静态同步方法:
package Test;
public class Test {
public static void main(String[] args) throws InterruptedException {
CustomThread uploadDetect1 = new CustomThread();
CustomThread uploadDetect2 = new CustomThread();
CustomThread uploadDetect3 = new CustomThread();
CustomThread uploadDetect4 = new CustomThread();
CustomThread uploadDetect5 = new CustomThread();
Thread t1 = new Thread(uploadDetect1);
Thread t2 = new Thread(uploadDetect2);
Thread t3 = new Thread(uploadDetect3);
Thread t4 = new Thread(uploadDetect4);
Thread t5 = new Thread(uploadDetect5);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Stu1 {
static int count = 100;
public static synchronized void func() {
count --;
int out = count;
System.out.println("Count : "+out);
}
}
class CustomThread implements Runnable {
Stu1 stu1 = new Stu1();
public void run() {
while(Stu1.count > 0) {
Stu1.func();
try {
Thread.sleep(4);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4、关于String的intern方法:
测试代码:
String str1 = new String("SEU")+ new String("Calvin");
System.out.println(str1.intern() == str1);
System.out.println(str1 == "SEUCalvin");
输出:
true
true
测试代码:
String str2 = "SEUCalvin";//新加的一行代码,其余不变
String str1 = new String("SEU")+ new String("Calvin");
System.out.println(str1.intern() == str1);
System.out.println(str1 == "SEUCalvin");
输出:
false
false
intern()方法能减少内存浪费。