关于线程锁的问题
synchronized 是对当前对象加锁 所不同的地方是 synchronized 在不实用静态声明static 的时候对的是当前对象加锁 ,而加了静态声明的时候对的是当前的类 加锁 实现了同步
Class A {
public synchronized methodA() {//对当前对象加锁
}
public methodB() {
synchronized(this){}//对当前对象加锁,与methodA用法相同
}
public static synchronized methodC() {}//对类加锁,即对所有此类的对象加锁
public methodD(){
synchronized(A.class){}//对类加锁,即对所有此类的对象加锁
}
}
如下例代码所示
public class MultiThread {
private int count=0;
public synchronized void printOut(String tag)throws InterruptedException {
if(tag.equals("a")){
count=100;
Thread.sleep(2000);
System.out.println("tag="+tag+",count="+count);
}else{
count=200;
System.out.println("tag="+tag+",count="+count);
}
}
public static void main(String args[]){
final MultiThread m1=new MultiThread();
final MultiThread m2=new MultiThread();
Thread t1=new Thread(new Runnable() {
public void run() {
try {
m1.printOut("a");
}catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable() {
public void run() {
try {
m2.printOut("b");
}catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
tag=b,count=200
tag=a,count=100
t1和t2 是同时执行的 synchronized 分别锁的是自身的那个实例化对象
当加了 static 的时候
public class MultiThread {
private static int count=0;
public static synchronized void printOut(String tag)throws InterruptedException {
if(tag.equals("a")){
count=100;
Thread.sleep(2000);
System.out.println("tag="+tag+",count="+count);
}else{
count=200;
System.out.println("tag="+tag+",count="+count);
}
}
public static void main(String args[]){
final MultiThread m1=new MultiThread();
final MultiThread m2=new MultiThread();
Thread t1=new Thread(new Runnable() {
public void run() {
try {
m1.printOut("a");
}catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable() {
public void run() {
try {
m2.printOut("b");
}catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
tag=a,count=100
tag=b,count=200
锁住了当前的类 因为t1先执行所以获得类锁 之后t2必须等待t1执行完
run方法之后才能获得锁
网友评论