类锁和对象锁,synchronized修饰static方法与非static方法的区别
当synchronized修饰一个static方法时,多线程下,获取的是类锁(即Class本身,注意:不是实例),作用范围是整个静态方法,作用的对象是这个类的所有对象。
当synchronized修饰一个非static方法时,多线程下,获取的是对象锁(即类的实例对象),作用范围是整个方法,作用对象是调用该方法的对象。
结论: 类锁和对象锁,一个是类的Class对象的锁,一个是类的实例的锁。
例子:synchronized修饰static方法与非static方法的区别
public class test_类锁与对象锁的区别 extends Thread{
public static int i = 0;
public static int j = 0;
public synchronized void inc(){
i ++;
}
public static synchronized void incs(){
j ++;
}
public void run() {
for (int x = 0; x < 10; x++) {
inc();
incs();
try {
Thread.sleep(33);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//不使用定线程池
Thread[] t = new Thread[100];
//创建子线程
for (int i = 0; i < t.length; i++) {
t[i] = new test_类锁与对象锁的区别();
}
//子线程开始
for (int i = 0; i < t.length; i++) {
t[i].start();
}
//join()方法的作用:让父线程等待子线程结束之后才能继续运行。
for (int i = 0; i < t.length; i++) {
t[i].join();
}
System.out.println("synchronized修饰非静态方法----"+test_类锁与对象锁的区别.i);
System.out.println("synchronized修饰静态方法----"+test_类锁与对象锁的区别.j);
}
}
效果:
synchronized修饰非静态方法----866
synchronized修饰静态方法----1000
例子:synchronized修饰static方法与非static方法,对象锁的解决方案
public class test_类锁与对象锁_解决方案 {
public static int i = 0;
public static int j = 0;
//synchronized修饰非静态方法
public synchronized void function() throws InterruptedException {
i++;
}
//synchronized修饰静态方法
public static synchronized void staticFunction()
throws InterruptedException {
j++;
}
public static void main(String[] args) {
final test_类锁与对象锁_解决方案 demo = new test_类锁与对象锁_解决方案();
//使用定长线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
staticFunction();
demo.function();
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
for (int i = 0; i < 1000; i++) {
fixedThreadPool.execute(t1);
}
fixedThreadPool.shutdown();
while(true){
if (fixedThreadPool.isTerminated()) {
System.out.println("synchronized修饰非静态方法----"+test_类锁与对象锁_解决方案.i);
System.out.println("synchronized修饰静态方法----"+test_类锁与对象锁_解决方案.j);
break;
}
}
}
}
效果:
synchronized修饰非静态方法----1000
synchronized修饰静态方法---1000
以上就是有关类锁和对象锁,synchronized修饰static方法与非static方法的区别,要了解更多类锁和对象锁,static和非static的知识,请关注学步园。