日期:2014-05-20  浏览次数:20750 次

同步锁问题

public class qweq {
private static int a = 0 ;

public static synchronized int a(){
System.out.println(a);
return a++;
}
public static synchronized void c(){
System.out.println("-------================="+a);
}
}
这是一个类里面的两个同步方法。。。


public class dcad {
public static void main(String[] args) {
new a().start();
while(true){
System.out.println("====main====");
qweq.c();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class a extends Thread{

public void run() {
while(true){
System.out.println("====thread====");
qweq.c();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

这是测试的main函数

====main====
====thread====
-------=================0
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====main====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0
====thread====
-------=================0

问题是:sleep(),方法应该是不释放锁的。 为什么 qweq.c()方法 在主线程sleep过程中 依然可以继续执行啊。。。

------解决方案--------------------
调用sleep()时,线程没得到对象锁。
------解决方案--------------------
你的sleep()放的地方不对,不管是主线程还是你创建的线程在sleep的过程中,它已经执行完一次qweq.c()这个方法,就会释放当前对象锁,下一个线程就有机会执行此方法;
------解决方案--------------------
探讨

你的sleep()放的地方不对,不管是主线程还是你创建的线程在sleep的过程中,它已经执行完一次qweq.c()这个方法,就会释放当前对象锁,下一个线程就有机会执行此方法;