用2个线程编写程序,交替打印 [英] Writing a program with 2 threads which prints alternatively
问题描述
我最近在接受采访时被问到这个问题。
I got asked this question recently in an interview.
编写一个包含两个线程(A和B)的程序,其中A打印1,B打印2,依此类推,直到达到50.
Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is reached.
我们如何做到这一点?
推荐答案
赋值的本质是演示线程如何发出另一个信号。最常见的方法是使用阻塞队列,但这里信号不携带任何信息,因此信号量就足够了。
The essence of the assignment is to demonstrate how a thread can signal another one. Most common way is to use blocking queues, but here a signal does not carry any information, so a Semaphore is sufficient.
创建用2个信号量参数化的线程类:输入和输出:
Create thread class which is parameterized with 2 Semaphores: input and output:
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 信号量
s并将它们传递给2个主题:
Create 2 Semaphore
s and pass them to 2 threads:
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);
注意信号量 a
和 b
以不同的顺序传递。
Note semaphores a
and b
are passed in different order.
这篇关于用2个线程编写程序,交替打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!