在 Java 中,線(xiàn)程間的同步和通信是確保多線(xiàn)程程序正確運(yùn)行的關(guān)鍵。以下是一些常用的方法和示例:
### 線(xiàn)程同步
線(xiàn)程同步用于防止多個(gè)線(xiàn)程同時(shí)訪(fǎng)問(wèn)共享資源,從而避免數(shù)據(jù)不一致的問(wèn)題。Java 提供了 `synchronized` 關(guān)鍵字來(lái)實(shí)現(xiàn)同步。
#### 同步方法
使用 `synchronized` 關(guān)鍵字修飾方法,確保同一時(shí)間只有一個(gè)線(xiàn)程可以執(zhí)行該方法。
```java
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
```
#### 同步塊
使用 `synchronized` 關(guān)鍵字修飾代碼塊,可以更細(xì)粒度地控制同步范圍。
```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;
}
}
}
```
### 線(xiàn)程通信
線(xiàn)程通信用于在多個(gè)線(xiàn)程之間傳遞信息。Java 提供了 `wait()`、`notify()` 和 `notifyAll()` 方法來(lái)實(shí)現(xiàn)線(xiàn)程通信。
#### 示例代碼
以下是一個(gè)生產(chǎn)者-消費(fèi)者模型的示例,展示了如何使用 `wait()` 和 `notify()` 方法進(jìn)行線(xiàn)程通信。
```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();
}
}
```
通過(guò)這些方法,Java 程序可以實(shí)現(xiàn)線(xiàn)程間的同步和通信,確保多線(xiàn)程程序的正確性和效率。