在 Java 中,線程間的同步和通信是確保多線程程序正確運行的關鍵。以下是一些常用的方法和示例:
### 線程同步
線程同步用于防止多個線程同時訪問共享資源,從而避免數(shù)據(jù)不一致的問題。Java 提供了 `synchronized` 關鍵字來實現(xiàn)同步。
#### 同步方法
使用 `synchronized` 關鍵字修飾方法,確保同一時間只有一個線程可以執(zhí)行該方法。
```java
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
```
#### 同步塊
使用 `synchronized` 關鍵字修飾代碼塊,可以更細粒度地控制同步范圍。
```java
public class Counter {
private int count = 0;
private final Object lock = new Object();
public void increment() {
synchronized (lock) {
count++;
}
}
public int getCount() {
synchronized (lock) {
return count;
}
}
}
```
### 線程通信
線程通信用于在多個線程之間傳遞信息。Java 提供了 `wait()`、`notify()` 和 `notifyAll()` 方法來實現(xiàn)線程通信。
#### 示例代碼
以下是一個生產(chǎn)者-消費者模型的示例,展示了如何使用 `wait()` 和 `notify()` 方法進行線程通信。
```java
class SharedResource {
private boolean flag = false;
public synchronized void produce() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Producing...");
flag = true;
notify();
}
public synchronized void consume() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consuming...");
flag = false;
notify();
}
}
public class ThreadCommunication {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(resource::produce);
Thread consumer = new Thread(resource::consume);
producer.start();
consumer.start();
}
}
```
通過這些方法,Java 程序可以實現(xiàn)線程間的同步和通信,確保多線程程序的正確性和效率。