基于java运用synchronized关键字解决多线程编程进程间同步和互斥问题的代码
时间: 2024-03-20 18:41:00 浏览: 94
以下是一个使用synchronized关键字解决多线程编程进程间同步和互斥问题的示例代码:
```
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized void decrement() {
count--;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.decrement();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.getCount());
}
}
```
在上面的代码中,Counter类中的increment()、decrement()和getCount()方法都使用了synchronized关键字,保证了同一时间只有一个线程能够访问这些方法。这样就避免了多线程同时对count变量进行修改导致的数据不一致的问题。在Main类中,创建了两个线程分别调用increment()和decrement()方法,最后打印出count变量的值。
阅读全文
相关推荐
















