gpt4 book ai didi

java - 编写一个有 2 个线程的程序,交替打印

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:35 28 4
gpt4 key购买 nike

我最近在面试中被问到这个问题。

Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is reached.

我们该怎么做?

最佳答案

赋值的本质是演示一个线程如何向另一个线程发送信号。最常见的方式是使用阻塞队列,但这里一个信号不携带任何信息,所以一个信号量就足够了。

创建用 2 个信号量参数化的线程类:输入和输出:

class ThreadPrinter implements Runnable {
int counter;
Semaphore ins, outs;

ThreadPrinter(int counter, Semaphore ins, Semaphore outs) {
this.counter = counter;
this.ins = ins;
this.outs = outs;
}

@Override
public void run() {
for (int i = 0; i < 25; i++) {
ins.aquire(); // wait for permission to run
System.out.println("" + counter);
outs.release(); // allow another thread to run
counter += 2;
}
}

创建 2 个 Semaphore 并将它们传递给 2 个线程:

Semaphore a = new Semaphore(1);  // first thread is allowed to run immediately
Semaphore b = new Semaphore(0); // second thread has to wait
ThreadPrinter tp1 = new ThreadPrinter(1, a, b);
ThreadPrinter tp2 = new ThreadPrinter(2, b, a);

注意信号量 ab 以不同的顺序传递。

关于java - 编写一个有 2 个线程的程序,交替打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9388838/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com