日期:2014-05-20 浏览次数:20753 次
public class Test extends Thread {
Aa a;
public Test(Aa a){
this.a = a;
}
public void run(){
a.visit();
}
public static void main(String[] args) {
Aa a = new Aa();
Thread thread1 = new Test(a);
Thread thread2 = new Test(a);
thread1.start();
thread2.start();
}
}
class Aa {
private static int i = 0;
public synchronized void visit() {
i++;
try{
Thread.sleep(1);
}catch(InterruptedException e){ }
System.out.println(i);
}
}
public void visit() {
synchronized (Aa.class) {
i++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(i);
}
}
class Aa {
private static Integer i = 0;
public void visit() {
synchronized (i) {
i++;
System.out.println(i);
}
}
}
package demo;
public class Test implements Runnable {
Aa a = new Aa();
public void run() {
a.visit();
}
public static void main(String[] args) {
// 使用同一个runnable对象,这样a对象也是同一个,这时候synchronized才生效
// 方法上的锁是锁的this!!锁的是当前对象!你把你家门锁了,别人进了你隔壁的人家里!你管的着么你!
Test test = new Test();
// 这时候创建了两个不同的a对象!不同的a对象!相当于两个家!分别有两把长的一样的锁!你进了一个家,锁上门,别人照样能进隔壁家的!
// Thread thread1 = new Test();
// Thread thread2 = new Test();
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();
}
}
class Aa {
private static int i = 0;
public synchronized void visit() {
i++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(i);
}
}