Java中如何实现线程通信?


•  在Java中,线程通信可以通过以下几种方式实现:
•  使用 wait()、notify() 和 notifyAll()
•  wait():使当前线程进入等待状态,直到其他线程调用 notify() 或 notifyAll()。
•  notify():唤醒在该对象监视器上等待的单个线程。
•  notifyAll():唤醒在该对象监视器上等待的所有线程。
•  示例代码:
class SharedResource {
    private int data;
    private boolean hasData = false;

    public synchronized void produce(int value) throws InterruptedException {
        while (hasData) {
            wait();
        }
        this.data = value;
        hasData = true;
        notify();
    }

    public synchronized int consume() throws InterruptedException {
        while (!hasData) {
            wait();
        }
        hasData = false;
        notify();
        return data;
    }
}

public class ProducerConsumerExample {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.produce(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = resource.consume();
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

•  使用 BlockingQueue
•  BlockingQueue 是一个线程安全的队列,常用于生产者-消费者模式。
•  示例代码:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerExample {
    public static void main(String[] args) {
        BlockingQueue queue = new LinkedBlockingQueue<>(10);
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    queue.put(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = queue.take();
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

•  使用 Lock 和 Condition
•  Lock 和 Condition 提供了更灵活的同步机制,可以替代 wait()、notify() 和 notifyAll()。
•  示例代码:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharedResourceWithLock {
    private int data;
    private boolean hasData = false;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void produce(int value) throws InterruptedException {
        lock.lock();
        try {
            while (hasData) {
                condition.await();
            }
            this.data = value;
            hasData = true;
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public int consume() throws InterruptedException {
        lock.lock();
        try {
            while (!hasData) {
                condition.await();
            }
            hasData = false;
            condition.signal();
            return data;
        } finally {
            lock.unlock();
        }
    }
}

public class LockConditionExample {
    public static void main(String[] args) {
        SharedResourceWithLock resource = new SharedResourceWithLock();
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.produce(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = resource.consume();
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

•  使用 Exchanger
•  Exchanger 是一个用于线程间交换数据的同步点。
•  示例代码:
import java.util.concurrent.Exchanger;

public class ExchangerExample {
    public static void main(String[] args) {
        Exchanger exchanger = new Exchanger<>();
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println("Produced: " + i);
                    exchanger.exchange(i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = exchanger.exchange(null);
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

•  使用 Semaphore
•  Semaphore 是一个计数信号量,通常用于限制对某些资源的访问。
•  示例代码:
import java.util.concurrent.Semaphore;

class SemaphoreSharedResource {
    private int data;
    private Semaphore semaphore = new Semaphore(1);

    public void produce(int value) throws InterruptedException {
        semaphore.acquire();
        try {
            this.data = value;
            System.out.println("Produced: " + value);
        } finally {
            semaphore.release();
        }
    }

    public int consume() throws InterruptedException {
        semaphore.acquire();
        try {
            System.out.println("Consumed: " + data);
            return data;
        } finally {
            semaphore.release();
        }
    }
}

public class SemaphoreExample {
    public static void main(String[] args) {
        SemaphoreSharedResource resource = new SemaphoreSharedResource();
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.produce(i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.consume();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

希望这些解释和示例代码能帮助你更好地理解Java中的线程通信机制。如果有任何其他问题或需要进一步的解释,请随时告诉我!

你可能感兴趣的:(java)