给我一个synchronized的案例
时间: 2023-02-08 22:24:00 浏览: 66
在Java中,`synchronized`关键字用于在多线程环境中保护共享资源。下面是一个简单的案例:
```
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
class CounterThread extends Thread {
private Counter counter;
public CounterThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class SynchronizedExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new CounterThread(counter);
Thread thread2 = new CounterThread(counter);
thread1.start();
thread2.start();
}
}
```
这个例子中,`Counter` 类是一个共享资源,它有一个变量 `count` 和两个方法 `increment()` 和 `getCount()`。 `increment()` 方法用于增加 `count` 的值,而 `getCount()` 方法用于获取 `count` 的值。
在这个例子中,我们使用了 `synchronized` 关键字来保护这个共享资源。这意味着在一个时刻只有一个线程能够访问 `increment()` 或 `getCount()` 方法。这样就可以避免多个线程同时访问共享资源导致的冲突。
在main里面我们创建了两个线程 使用同一个Counter 实例,并且分别调用它的 `run()` 方法,导致在两个不同的线程中调用 `increment()` 方法,但因为increment方法使用了synchronized关键字,所以最后count会是2000 。