多线程 - synchronized修饰实例方法、修饰静态方法、修饰代码块
static synchronized 和 synchronized 修饰普通方法的区别在于:
static synchronized 是在类级别上获取锁,而 synchronized 是在对象级别上获取锁。
在 static synchronized 方法中,获取的是类级别的锁,不同的对象共享该锁,
只有当一个线程持有该类的锁时,才能够调用该类的其他 static synchronized 方法。
而在 synchronized 方法中,获取的是对象级别的锁,每个对象都有自己的锁,不同的对象之间互不影响。
对于 synchronized 代码块和方法的区别,主要在于锁的粒度不同。
synchronized 代码块可以在代码块中只锁定需要同步的部分,而 synchronized 方法会锁定整个方法。
因此,如果一个类中有多个同步方法,使用 synchronized 代码块可以提高并发性能,减少锁的竞争。
修饰实例方法
package com.lfsun.highconcurrency000.mysynchronized;
/**
* 修饰实例方法
*/
public class MySynchronizedDemo1 {
// 实例变量
private int count = 0;
// synchronized 修饰实例方法
public synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
MySynchronizedDemo1 demo = new MySynchronizedDemo1();
// 创建两个线程
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
demo.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
demo.increment();
}
});
thread1.start();
thread2.start();
// 等待两个线程执行完成
thread1.join();
thread2.join();
// 输出计数器的值
System.out.println("Count: " + demo.count);
}
}
修饰静态方法
package com.lfsun.highconcurrency000.mysynchronized;
/**
* 修饰静态方法
*/
public class MySynchronizedDemo2 {
// 静态变量
private static int count = 0;
// synchronized 修饰静态方法
public static synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
// 创建两个线程
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
MySynchronizedDemo2.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
MySynchronizedDemo2.increment();
}
});
thread1.start();
thread2.start();
// 等待两个线程执行完成
thread1.join();
thread2.join();
// 输出计数器的值
System.out.println("Count: " + MySynchronizedDemo2.count);
}
}
修饰代码块
package com.lfsun.highconcurrency000.mysynchronized;
/**
* 修饰代码块
*/
public class MySynchronizedDemo3 {
// 实例变量
private int count = 0;
public void increment() {
// synchronized 修饰代码块
synchronized (this) {
count++;
}
}
public static void main(String[] args) throws InterruptedException {
MySynchronizedDemo3 demo = new MySynchronizedDemo3();
// 创建两个线程
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
demo.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
demo.increment();
}
});
thread1.start();
thread2.start();
// 等待两个线程执行完成
thread1.join();
thread2.join();
// 输出计数器的值
System.out.println("Count: " + demo.count);
}
}
还没有评论,来说两句吧...