java多线程线程同步示例
时间: 2023-09-24 19:05:59 浏览: 51
以下是一个简单的 Java 多线程同步示例,使用了 synchronized 关键字:
```java
public class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + counter.getCount());
}
}
```
在上述示例中,Counter 类中的 increment() 和 getCount() 方法都使用了 synchronized 关键字,这表示这两个方法都是同步的。这意味着在同一时间内只能有一个线程访问这两个方法。这样就可以避免多个线程同时对 count 进行修改,从而保证程序的正确性。在 main() 方法中,我们创建了两个线程来分别调用 Counter 类中的 increment() 方法,最终输出 count 的值。