admin 管理员组

文章数量: 1087139


2024年3月21日发(作者:verifysignatures是什么意思)

synchronized用法示例

`synchronized`是Java中的一个关键字,用于控制多个线程对共享资

源的访问。它可以确保在同一时刻,只有一个线程可以执行某个方法

或代码块,从而防止多个线程同时访问导致的数据不一致问题。

下面是`synchronized`的一些用法示例:

### 1. 同步实例方法

当`synchronized`修饰一个实例方法时,它锁定的是当前实例对象

(`this`)。

```java

public class MyClass {

public synchronized void doSomething() {

// 只有获得当前对象锁的线程才能执行这里的代码

}

}

```

### 2. 同步静态方法

当`synchronized`修饰一个静态方法时,它锁定的是当前类的`Class`

对象。

```java

public class MyClass {

public static synchronized void doSomethingStatic() {

// 只有获得对象锁的线程才能执行这里的代

}

}

```

### 3. 同步代码块

`synchronized`还可以用于同步代码块,可以指定锁定的对象。

```java

public class MyClass {

private final Object lock = new Object();

public void doSomethingWithBlock() {

synchronized (lock) {

// 只有获得lock对象锁的线程才能执行这里的代码

}

}

}

```

### 4. 在多线程环境中使用

当在多线程环境中使用`synchronized`时,通常用于保护共享资源,

防止多个线程同时访问导致的数据不一致。

```java

public class ThreadSafeCounter {

private int count = 0;

public synchronized void increment() {

count++;

}

public synchronized void decrement() {

count--;

}

public synchronized int getCount() {

return count;

}

public static void main(String[] args) {

ThreadSafeCounter counter = new ThreadSafeCounter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

ent();

}

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

ent();

}

});

();

();

try {

();

();

} catch (InterruptedException e) {

tackTrace();

}

n("Final count: " +

nt());

}

}

```

在上面的示例中,`ThreadSafeCounter`类中的`increment`、

`decrement`和`getCount`方法都被`synchronized`修饰,以确保在多

线程环境中对`count`变量的访问是线程安全的。


本文标签: 线程 访问 对象 才能 执行