举一个synchronized修饰变量的例子
时间: 2023-07-20 10:32:22 浏览: 67
`synchronized` 不可以直接修饰变量,但是可以通过 `synchronized` 修饰的代码块来保护变量的读写操作。例如,在多线程环境下,需要保证一个共享变量 `count` 的原子性操作,可以使用如下方式实现:
```java
public class Counter {
private int count;
public void increment() {
synchronized (this) {
count++;
}
}
public int getCount() {
synchronized (this) {
return count;
}
}
}
```
上面的代码中,`synchronized` 关键字用来保护 `count` 变量的读写操作,确保它们的原子性。在 `increment()` 方法和 `getCount()` 方法中,都使用了 `synchronized (this)` 代码块,将 `this` 对象作为锁对象,保证同一时间只有一个线程可以操作 `count` 变量。这样可以保证在多线程环境下,`count` 变量的值不会出现错误的结果。
相关问题
请给出一个Java synchronized例子
当多个线程同时访问共享资源时,为了避免数据竞争和不一致的结果,可以使用Java中的synchronized关键字来实现线程同步。下面是一个简单的Java synchronized示例:
```java
public class SynchronizedExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
SynchronizedExample example = new SynchronizedExample();
// 创建多个线程
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
// 启动线程
thread1.start();
thread2.start();
// 等待线程执行完毕
thread1.join();
thread2.join();
// 输出结果
System.out.println("Count: " + example.count);
}
}
```
在上面的示例中,我们创建了一个SynchronizedExample类,其中包含一个共享变量count和一个使用synchronized修饰的increment()方法。两个线程分别调用increment()方法来对count进行累加操作。由于increment()方法被synchronized修饰,同一时刻只能有一个线程访问该方法,确保了count的操作是原子性的,避免了数据竞争。最后输出结果为2000,表示两个线程对count进行了正确的累加操作。
举个例子
好的,下面是一个使用synchronized关键字实现同步锁定的例子:
```
public class SynchronizedExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
```
在这个例子中,`increment()`和`getCount()`方法都被`synchronized`关键字修饰,以达到同步锁定的效果。当一个线程正在执行`increment()`或`getCount()`方法时,其他线程无法访问这两个方法,直到该线程执行完毕并释放锁为止。这样就能够确保`count`变量的值能够正确地被更新和读取,避免了多线程并发访问的问题。