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);
}
}
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);
}
}
不过这样不科学。
科学的还是1楼的做法。
public void visit() {
synchronized (Aa.class) {
i++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(i);
}
}
祝lz学习进步,加油,更多关于多线程的学习交流欢迎访问:
http://blog.csdn.net/ysjian_pingcx/article/category/1861379
简单的方法,就是在visit方法前再加上static,这样就算是两个Aa,也要竞争同一个静态方法操作权。或者是将i改成Integer,对i加锁操作:class Aa {
private static Integer i = 0; public void visit() {
synchronized (i) {
i++;
System.out.println(i);
}
}
}
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);
}}
没有完全理解锁的概念。可以去看看<<java并发编程实战>>