线程同步与互斥Java代码
时间: 2024-05-16 08:17:26 浏览: 16
线程同步和互斥是确保多个线程正确协同工作的关键。在Java中,可以通过使用`synchronized`关键字来实现线程同步和互斥。下面是一个简单的示例代码:
```java
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
class MyThread extends Thread {
private Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
MyThread thread1 = new MyThread(counter);
MyThread thread2 = new MyThread(counter);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount());
}
}
```
在这个示例代码中,`Counter`类是一个计数器,包含两个同步方法:`increment()`和`getCount()`。`increment()`方法递增计数器的值,`getCount()`方法返回计数器的当前值。`MyThread`类是一个线程,它接收一个`Counter`对象并在其`run()`方法中重复调用`increment()`方法。在`main()`方法中,创建两个`MyThread`对象并启动它们。使用`join()`方法等待这两个线程完成,然后输出计数器的值。
使用`synchronized`关键字确保`increment()`和`getCount()`方法在同一时刻只能被一个线程访问。这样可以确保计数器的值在多个线程之间同步,并避免竞态条件的问题。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)