当前位置:首页 > Java

Java线程如何通讯

2026-03-03 13:33:58Java

Java线程通讯的方法

Java线程通讯主要通过共享内存和消息传递两种方式实现。以下是常见的线程通讯方法:

共享变量

使用共享变量是最基础的线程通讯方式。多个线程可以访问同一个对象的成员变量或静态变量。

public class SharedVariableExample {
    private static boolean flag = false;

    public static void main(String[] args) {
        new Thread(() -> {
            while (!flag) {
                // 等待flag变为true
            }
            System.out.println("Flag is now true");
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true;
            System.out.println("Flag set to true");
        }).start();
    }
}

wait()/notify()/notifyAll()

这些是Object类的方法,必须在同步块或同步方法中使用。

public class WaitNotifyExample {
    private final Object lock = new Object();

    public void doWait() throws InterruptedException {
        synchronized (lock) {
            System.out.println("Waiting...");
            lock.wait();
            System.out.println("Resumed");
        }
    }

    public void doNotify() {
        synchronized (lock) {
            System.out.println("Notifying...");
            lock.notify();
        }
    }
}

BlockingQueue

BlockingQueue接口提供了线程安全的队列实现,支持阻塞操作。

public class BlockingQueueExample {
    private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

    public void producer() throws InterruptedException {
        queue.put("Message");
    }

    public void consumer() throws InterruptedException {
        String message = queue.take();
    }
}

CountDownLatch

允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。

public class CountDownLatchExample {
    private final CountDownLatch latch = new CountDownLatch(3);

    public void worker() {
        // 工作代码
        latch.countDown();
    }

    public void await() throws InterruptedException {
        latch.await();
        System.out.println("All workers completed");
    }
}

CyclicBarrier

允许一组线程互相等待,直到到达某个公共屏障点。

public class CyclicBarrierExample {
    private final CyclicBarrier barrier = new CyclicBarrier(3);

    public void worker() throws BrokenBarrierException, InterruptedException {
        // 工作代码
        barrier.await();
    }
}

Semaphore

控制同时访问特定资源的线程数量。

public class SemaphoreExample {
    private final Semaphore semaphore = new Semaphore(3);

    public void accessResource() throws InterruptedException {
        semaphore.acquire();
        try {
            // 访问资源
        } finally {
            semaphore.release();
        }
    }
}

Exchanger

允许两个线程在集合点交换对象。

public class ExchangerExample {
    private final Exchanger<String> exchanger = new Exchanger<>();

    public void threadA() throws InterruptedException {
        String received = exchanger.exchange("Data from A");
    }

    public void threadB() throws InterruptedException {
        String received = exchanger.exchange("Data from B");
    }
}

PipedInputStream/PipedOutputStream

提供线程间的管道通讯。

public class PipedStreamExample {
    private final PipedInputStream in = new PipedInputStream();
    private final PipedOutputStream out = new PipedOutputStream();

    public PipedStreamExample() throws IOException {
        in.connect(out);
    }

    public void writer() throws IOException {
        out.write("Hello".getBytes());
    }

    public void reader() throws IOException {
        byte[] buffer = new byte[1024];
        int len = in.read(buffer);
        String message = new String(buffer, 0, len);
    }
}

选择哪种线程通讯方式取决于具体应用场景。共享变量适合简单场景,wait/notify适合条件等待,BlockingQueue适合生产者消费者模式,CountDownLatch适合一次性等待,CyclicBarrier适合可重用屏障,Semaphore适合资源池管理,Exchanger适合双向交换,管道流适合字节流通讯。

Java线程如何通讯

标签: 线程通讯
分享给朋友:

相关文章

php实现线程

php实现线程

在PHP中实现多线程功能需要借助扩展或第三方库,因为PHP本身是单线程设计的语言。以下是几种常见的方法: 使用pthreads扩展(PHP 7以下版本) pthreads是一个PHP扩展,允许在P…

php线程实现

php线程实现

在PHP中实现多线程可以通过多种方式,以下是常见的方法和示例: 使用pthreads扩展 pthreads是PHP的一个多线程扩展,适用于PHP 7.2及以上版本(Windows需ZTS版本)。…

js实现线程

js实现线程

JavaScript 是单线程语言,但可以通过以下方法模拟多线程或实现并发操作: Web Worker Web Worker 允许在后台运行脚本,与主线程并行执行。创建一个新的 Worker 线程…

js 实现线程

js 实现线程

在JavaScript中实现类似线程的功能可以通过以下几种方法实现,尽管JavaScript本身是单线程的,但通过异步编程或Web Worker可以实现并行处理的效果。 使用Web Worker…

js实现同步通讯

js实现同步通讯

同步通讯的实现方法 在JavaScript中,同步通讯通常指代码按照顺序执行,每一步操作完成后再进行下一步。以下是几种常见的同步通讯实现方法: 使用XMLHttpRequest同步请求 通过设置X…

java如何让线程停止

java如何让线程停止

停止线程的方法 在Java中,线程的停止可以通过以下几种方式实现,每种方式有不同的适用场景和注意事项。 使用标志位控制线程退出 通过设置一个共享的volatile变量作为标志位,线程在运行时检查…